﻿using AutoMapper;
using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.IT;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.TD;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.TD
{
    public partial class TD_AllocateBusiness : BaseBusiness<TD_Allocate>, ITD_AllocateBusiness, ITransientDependency
    {
        readonly IMapper _mapper;
        readonly IOperatorDept _opdept;
        public TD_AllocateBusiness(IDbAccessor db, IServiceProvider svcProvider, IOperator @operator, IMapper mapper, IOperatorDept @opdept)
            : base(db)
        {
            _operator = @operator;
            _mapper = mapper;
            _opdept = @opdept;
        }

        #region 外部接口

        public async Task<PageResult<TD_Allocate>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<TD_Allocate>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<TD_Allocate, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        [DataDeleteLog(UserLogType.调拨管理, "Code", "调拨单")]
        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        /// <summary>
        /// 调拨出入库的列表信息
        /// </summary>
        /// <param name="cateqrcode">调拨单的二维码</param>
        /// <param name="status">出入库状态</param>
        /// <returns></returns>
        public async Task<List<AllocatePackDetailDTO>> GetAllocatePackListDataAsync(string cateqrcode, int status)
        {
            string cateId = cateqrcode.Split(',')?[1].ToString();
            string sqlMain = string.Empty;
            if (status == 0)
            {
                sqlMain = @"  select * from (
 select '' as Id,a.AllocateId,a.PackId,a.MaterialId,a.JobId,m.Spec as MaterialSpec,b.BoxName,CONCAT(d.`Name`,'/',e.`Name`,'/',c.`Name`) as LocalName,a.PackNums as StockNumber,a.CreateTime from TD_AllocatePackDetail as a join PB_PackList as b on a.PackId=b.Id join PB_Material as m on a.MaterialId=m.Id join PB_Location as c on a.FormLocaId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id where a.`Status`={1} and b.PackageType=0 and a.AllocateId='{0}'  
 UNION ALL  
 select '' as Id,AllocateId,PackId,'' as MaterialId,JobId,MaterialSpec,BoxName,LocalName,SUM(PackNums) as StockNumber,CreateTime from ( select a.AllocateId,a.PackId,a.MaterialId,a.JobId,'' as MaterialSpec,b.BoxName,CONCAT(d.`Name`,'/',e.`Name`,'/',c.`Name`) as LocalName,a.PackNums,DATE_FORMAT(a.CreateTime,'%Y-%m-%d') as CreateTime from TD_AllocatePackDetail as a join PB_PackList as b on a.PackId=b.Id join PB_Material as m on a.MaterialId=m.Id join PB_Location as c on a.FormLocaId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id where a.`Status`={1} and b.PackageType=1 and a.AllocateId= '{0}' ) as tt group by AllocateId,PackId,MaterialSpec,BoxName,LocalName,CreateTime,JobId  
 UNION ALL  
 select a.Id,a.AllocateId,a.PackId,a.MaterialId,a.JobId,b.Spec as MaterialSpec,b.Name as BoxName,CONCAT(d.`Name`,'/',e.`Name`,'/',c.`Name`) as LocalName,a.PackNums as StockNumber,a.CreateTime from TD_AllocatePackDetail as a join PB_Material as b on a.MaterialId=b.Id join PB_Location as c on a.FormLocaId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id where a.`Status`={1} and a.PackId=''  and a.AllocateId= '{0}'  
 ) as t order by CreateTime desc  ";
            }
            else
            {
                sqlMain = @"  select * from ( 
select '' as Id,a.AllocateId,a.PackId,a.MaterialId,a.JobId,m.Spec as MaterialSpec,b.BoxName,CONCAT(d.`Name`,'/',e.`Name`,'/',c.`Name`) as LocalName,a.PackNums as StockNumber,a.CreateTime from TD_AllocatePackDetail as a join PB_PackList as b on a.PackId=b.Id join PB_Material as m on a.MaterialId=m.Id join PB_Location as c on a.ToLocaId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id where a.`Status`={1} and b.PackageType=0 and a.AllocateId='{0}' 
UNION ALL 
select '' as Id,AllocateId,PackId,'' as MaterialId,JobId,MaterialSpec,BoxName,LocalName,SUM(PackNums) as StockNumber,CreateTime from ( 
select a.AllocateId,a.PackId,a.MaterialId,a.JobId,'' as MaterialSpec,b.BoxName,CONCAT(d.`Name`,'/',e.`Name`,'/',c.`Name`) as LocalName,a.PackNums,DATE_FORMAT(a.CreateTime,'%Y-%m-%d') as CreateTime from TD_AllocatePackDetail as a join PB_PackList as b on a.PackId=b.Id join PB_Material as m on a.MaterialId=m.Id join PB_Location as c on a.ToLocaId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id where a.`Status`={1} and b.PackageType=1 and a.AllocateId= '{0}' 
) as tt group by AllocateId,PackId,JobId,MaterialSpec,BoxName,LocalName,CreateTime 
UNION ALL 
select a.Id,a.AllocateId,a.PackId,a.MaterialId,a.JobId,b.Spec as MaterialSpec,b.Name as BoxName,CONCAT(d.`Name`,'/',e.`Name`,'/',c.`Name`) as LocalName,a.PackNums as StockNumber,a.CreateTime from TD_AllocatePackDetail as a join PB_Material as b on a.MaterialId=b.Id join PB_Location as c on a.ToLocaId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id where a.`Status`={1} and a.PackId=''  and a.AllocateId= '{0}' 
) as t order by CreateTime desc ";

            }
            string sql = string.Format(sqlMain, cateId, status);
            return await Db.GetListBySqlAsync<AllocatePackDetailDTO>(sql);
        }

        /// <summary>
        /// 调拨出入库获取包的信息
        /// </summary>
        /// <param name="PackQrCode">包二维码</param>
        /// <param name="cateqrcode">调拨单的二维码</param>
        /// <param name="status">出入库状态</param>
        /// <returns></returns>
        public async Task<AllocatePackDTO> GetAllocatePackDataAsync(string PackQrCode, string cateqrcode, int status)
        {
            //包Id
            string packid = PackQrCode.Split(',')?[1].ToString();
            //调拨单Id
            string cateid = cateqrcode.Split(',')?[1].ToString();

            PB_PackList PackList = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packid).FirstOrDefaultAsync();
            if (PackList != null)
            {
                Expression<Func<PB_PackMaterialCount, PB_Material, AllocatePackMaterialDetailDTO>> select = (a, b) => new AllocatePackMaterialDetailDTO
                {
                    PackId = a.PackId,
                    MaterialId = a.MaterialId,
                    MaterialName = b.Name,
                    MaterialCode = b.Code,
                    MaterialSpec = b.Spec,
                    ProductCode = b.ProductCode,
                    Nums = a.Nums
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_PackMaterialCount>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                List<AllocatePackMaterialDetailDTO> AllocatePackMaterialDetail = await q.Where(x => x.PackId == packid).ToListAsync();

                //获取调拨单物料的调拨数量
                List<TD_AllocateDetail> AllocateDetail = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == cateid).ToListAsync();

                //出库
                if (status == 0)
                {
                    //获取调拨单已出库的物料
                    List<TD_AllocatePackDetail> AllocatePackDetail = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.AllocateId == cateid && x.Status == 0).ToListAsync();
                    var allmater = AllocatePackDetail.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).ToList();

                    foreach (var item in AllocatePackMaterialDetail)
                    {
                        var itemdata = allmater.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                        var materdata = AllocateDetail.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                        if (materdata == null)
                        {
                            throw new BusException("请检查包对应的物料与调拨单的物料是否匹配");
                        }
                        if (itemdata != null)
                        {
                            item.RemainingQuantity = (materdata.AllocateNum - (itemdata == null ? 0 : itemdata.Nums));
                        }
                        else
                        {
                            item.RemainingQuantity = materdata.AllocateNum;
                        }
                    }
                }
                else
                {
                    //获取调拨单已入库的物料
                    List<TD_AllocatePackDetail> AllocatePackDetail = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.AllocateId == cateid && x.Status == 1).ToListAsync();
                    var allmater = AllocatePackDetail.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).ToList();

                    foreach (var item in AllocatePackMaterialDetail)
                    {
                        var itemdata = allmater.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                        var materdata = AllocateDetail.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                        if (materdata == null)
                        {
                            throw new BusException("请检查包对应的物料与调拨单的物料是否匹配");
                        }
                        if (itemdata != null)
                        {
                            item.RemainingQuantity = (materdata.AllocateNum - (itemdata == null ? 0 : itemdata.Nums));
                        }
                        else
                        {
                            item.RemainingQuantity = materdata.AllocateNum;
                        }
                    }
                }

                AllocatePackDTO supack = new AllocatePackDTO();
                supack.PackId = PackList.Id;
                supack.PackQrCode = PackList.QrCode;
                supack.BoxName = PackList.BoxName;
                supack.Nums = PackList.Nums;
                supack.AllocatePackMaterialDetail = AllocatePackMaterialDetail;
                return supack;
            }
            else
            {
                throw new BusException("请扫描正确的包");
            }
        }

        /// <summary>
        /// 调拨出库
        /// </summary>
        /// <param name="data"></param>
        /// 增加混合包和单个物料调拨  2022-02-23  赵锦涛
        /// <returns></returns>
        [Transactional]
        public async Task UpcateOutStorageAsync(AllocateDTO data)
       {
            //调拨单Id
            string allocateId = data.cateqrcode.Split(',')?[1].ToString();
            //货位Id
            string locaId = data.locaqrcode.Split(',')?[1].ToString();
            //包Id
            string packId = string.Empty;
            string materialId = string.Empty;
            string jobid = string.Empty;
            string packmodel = data.packqrcode.Split(',')?[0].ToString();
            Base_LinkType linktypedata = await _opdept.GetLinkType("MaterialCode");
            if (packmodel == "13")
            {
                packId = data.packqrcode.Split(',')?[1].ToString();
            }
            else if (packmodel == "04")
            {
                var model = data.packqrcode.Split(',');
                if (model.Length > 2)
                {
                    if (model.Length < 4)
                    {
                        throw new BusException("请扫描正确的二维码信息");
                    }
                    else
                    {
                        materialId = model?[3].ToString();
                    }
                }
                else
                {
                    materialId = model?[1].ToString();
                }
                //合并重复物料指向新的物料Id
                PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                if (!materdata.TransferId.IsNullOrEmpty())
                {
                    materialId = materdata.TransferId;
                }
            }
            else if (packmodel == "14")
            {
                jobid = data.packqrcode.Split(',')?[1].ToString();
                ////查询单个成品是否绑定包信息
                //PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid && x.PackStatus == 0).FirstOrDefaultAsync();
                //if (jobdata != null)
                //{
                //    if (!jobdata.PackId.IsNullOrEmpty())
                //    {
                //        packmodel = "13";
                //        packId = jobdata.PackId;
                //    }
                //}
            }
            string sqlMain = string.Empty;
            List<TD_AllocatePackDetail> AllocatePackDetailList = new List<TD_AllocatePackDetail>();
            List<PB_StockLog> StockLogList = new List<PB_StockLog>();
            List<PB_Unpacking> UnpackingList = new List<PB_Unpacking>();
            List<PB_UnpackingDetail> UnpackingDetailList = new List<PB_UnpackingDetail>();

            Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            if (packmodel == "13")
            {
                PB_PackList PB_PackListdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId).FirstOrDefaultAsync();
                if (PB_PackListdata == null)
                {
                    throw new BusException("请扫描正确的包二维码!");
                }
                if (PB_PackListdata.PackageType == 0)
                {
                    //查询库里的包信息
                    IT_LocalDetail itdetaildata = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId && x.LocalId == locaId).FirstOrDefaultAsync();
                    if (itdetaildata != null)
                    {
                        //查询调拨单物料明细信息
                        TD_AllocateDetail tddetaildata = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == allocateId && x.FromLocalId == itdetaildata.LocalId && x.MaterialId == itdetaildata.MaterialId).FirstOrDefaultAsync();
                        if (tddetaildata != null)
                        {
                            //查询调拨单物料对应的包信息
                            List<TD_AllocatePackDetail> lisdata = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.MaterialId == itdetaildata.MaterialId && x.AllocateId == allocateId).ToListAsync();
                            //调拨单物料对应包里的物料数量和调拨单物料数量比较
                            double dnum = 0;
                            foreach (var item in lisdata)
                            {
                                dnum += Convert.ToDouble(item.PackNums);
                            }
                            dnum += Convert.ToDouble(itdetaildata.Num);
                            if (dnum <= tddetaildata.AllocateNum)
                            {
                                //添加调拨单包明细
                                TD_AllocatePackDetail tdpackdata = new TD_AllocatePackDetail();
                                tdpackdata.Id = IdHelper.GetId();
                                tdpackdata.ParentId = tddetaildata.Id;
                                tdpackdata.AllocateId = allocateId;
                                tdpackdata.MaterialId = tddetaildata.MaterialId;
                                tdpackdata.PackId = packId;
                                tdpackdata.PackNums = itdetaildata.Num;
                                tdpackdata.FormLocaId = itdetaildata.LocalId;
                                tdpackdata.ToLocaId = "";
                                tdpackdata.Status = 0;
                                tdpackdata.CreateTime = DateTime.Now;
                                tdpackdata.CreatorId = _operator.UserId;
                                tdpackdata.Deleted = false;
                                tdpackdata.OldOrNew = itdetaildata.OldOrNew;
                                tdpackdata.JobId = "";
                                AllocatePackDetailList.Add(tdpackdata);

                                //增加出库日志
                                PB_StockLog logdata = new PB_StockLog();
                                logdata.Id = IdHelper.GetId();
                                logdata.PackId = packId;
                                logdata.StorId = itdetaildata.StorId;
                                logdata.LocationId = itdetaildata.LocalId;
                                logdata.StockNumber = itdetaildata.Num;
                                logdata.CreateTime = DateTime.Now;
                                logdata.CreatorId = _operator.UserId;
                                logdata.CreatorName = basedata.RealName;
                                logdata.Deleted = false;
                                logdata.OperatorId = _operator.UserId;
                                logdata.State = 3;
                                logdata.OldOrNew = itdetaildata.OldOrNew;
                                logdata.JobId = "";
                                StockLogList.Add(logdata);

                                //删除库存明细
                                sqlMain += @" delete from IT_LocalDetail where PackId='" + packId + "'; ";
                                //删除PB_Stock
                                sqlMain += @" delete from PB_Stock where PackId='" + packId + "' and StorId='" + itdetaildata.StorId + "' and LocationId='" + itdetaildata.LocalId + "'; ";

                                //库存汇总减去出库的数量
                                if (itdetaildata.OldOrNew == 0)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + itdetaildata.Num + ",ScanNum=IFNULL(ScanNum,0)-" + itdetaildata.Num + " where StorId='" + itdetaildata.StorId + "' and LocalId='" + itdetaildata.LocalId + "' and MaterialId='" + itdetaildata.MaterialId + "'; ";
                                }
                                else if (itdetaildata.OldOrNew == 1)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + itdetaildata.Num + ",ScanNum=IFNULL(ScanNum,0)-" + itdetaildata.Num + " where StorId='" + itdetaildata.StorId + "' and LocalId='" + itdetaildata.LocalId + "' and MaterialId='" + itdetaildata.MaterialId + "'; ";
                                }

                                //减去物料的审核前数量
                                sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)-" + itdetaildata.Num + " where Id='" + itdetaildata.MaterialId + "'; ";

                                //修改包的状态为已出库
                                sqlMain += @" update PB_PackList set Status='4',OutStorTime=NOW() where Id='" + packId + "'; ";

                            }
                            else
                            {
                                throw new BusException("下架数量超过调拨数量请先拆包后操作");
                            }
                        }
                        else
                        {
                            throw new BusException("请检查货位,包的物料信息与调拨单的物料信息是否匹配");
                        }
                    }
                    else
                    {
                        throw new BusException("请扫描仓库内正确的包信息");
                    }
                }
                else if (PB_PackListdata.PackageType == 1)
                {
                    //获取库内混合包的信息
                    var locadetaillist = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId && x.LocalId == locaId).ToListAsync();
                    if (locadetaillist.Count == 0)
                    {
                        throw new BusException("请扫描仓库内正确的包信息");
                    }
                    //获取调拨单的物料明细信息
                    Expression<Func<TD_AllocateDetail, TD_AllocatePackDetail, TD_AllocateDetailListDTO>> select = (a, b) => new TD_AllocateDetailListDTO
                    {
                        Id = a.Id,
                        AllocateId = a.AllocateId,
                        FromStorId = a.FromStorId,
                        FromlocalId = a.FromLocalId,
                        ToStorId = a.ToStorId,
                        ToLocalId = a.ToLocalId,
                        MaterialId = a.MaterialId,
                        AllocateNum = a.AllocateNum,
                        PackId = b.PackId,
                        PackNums = b.PackNums
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in Db.GetIQueryable<TD_AllocateDetail>().AsExpandable()
                            join b in Db.GetIQueryable<TD_AllocatePackDetail>() on a.Id equals b.ParentId into ab
                            from b in ab.DefaultIfEmpty()
                            select @select.Invoke(a, b);
                    var AllDetaillist = await q.Where(x => x.AllocateId == allocateId).ToListAsync();
                    //根据调拨单物料分组查询物料已出库多少
                    var alllistdata = AllDetaillist.GroupBy(x => new { x.Id, x.AllocateId, x.FromStorId, x.FromlocalId, x.ToStorId, x.ToLocalId, x.MaterialId, x.AllocateNum }).Select(x => new
                    {
                        Id = x.Key.Id,
                        AllocateId = x.Key.AllocateId,
                        FromStorId = x.Key.FromStorId,
                        FromlocalId = x.Key.FromlocalId,
                        ToStorId = x.Key.ToStorId,
                        ToLocalId = x.Key.ToLocalId,
                        MaterialId = x.Key.MaterialId,
                        AllocateNum = x.Key.AllocateNum,
                        PackNums = x.Sum(n => n.PackNums)
                    }).ToList();
                    //对比混合包是否满足调拨单物料明细需求
                    //默认都满足
                    bool contrast = true;
                    foreach (var item in locadetaillist)
                    {
                        //混合包的物料信息匹配调拨单的物料信息
                        var itemdata = alllistdata.Where(x => x.MaterialId == item.MaterialId && x.FromlocalId == item.LocalId).FirstOrDefault();
                        if (itemdata != null)
                        {
                            //获取调拨单物料的剩余调拨数量
                            double dnum = itemdata.AllocateNum - Convert.ToDouble(itemdata.PackNums);
                            //包里的物料数量和调拨单物料的剩余数量做对比,满足为true,不满足为false
                            if (item.Num > dnum)
                            {
                                contrast = false;
                            }
                        }
                        else
                        {
                            contrast = false;
                        }
                    }
                    //不满足提示
                    if (contrast == false)
                    {
                        throw new BusException("请检查货位,包的物料信息与调拨单的物料信息是否匹配");
                    }
                    string strStorId = "";
                    string strLocalId = "";
                    foreach (var item in locadetaillist)
                    {
                        strStorId = item.StorId;
                        strLocalId = item.LocalId;

                        var itemdata = alllistdata.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                        //添加调拨单包明细
                        TD_AllocatePackDetail tdpackdata = new TD_AllocatePackDetail();
                        tdpackdata.Id = IdHelper.GetId();
                        tdpackdata.ParentId = itemdata.Id;
                        tdpackdata.AllocateId = allocateId;
                        tdpackdata.MaterialId = item.MaterialId;
                        tdpackdata.PackId = packId;
                        tdpackdata.PackNums = item.Num;
                        tdpackdata.FormLocaId = item.LocalId;
                        tdpackdata.ToLocaId = "";
                        tdpackdata.Status = 0;
                        tdpackdata.CreateTime = DateTime.Now;
                        tdpackdata.CreatorId = _operator.UserId;
                        tdpackdata.Deleted = false;
                        tdpackdata.OldOrNew = item.OldOrNew;
                        tdpackdata.JobId = "";
                        AllocatePackDetailList.Add(tdpackdata);

                        //库存汇总减去出库的数量
                        if (item.OldOrNew == 0)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                        }
                        else if (item.OldOrNew == 1)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                        }
                        //减去物料的审核前数量
                        sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where Id='" + item.MaterialId + "'; ";

                    }

                    //增加出库日志
                    PB_StockLog logdata = new PB_StockLog();
                    logdata.Id = IdHelper.GetId();
                    logdata.PackId = packId;
                    logdata.StorId = strStorId;
                    logdata.LocationId = strLocalId;
                    logdata.StockNumber = PB_PackListdata.Nums;
                    logdata.CreateTime = DateTime.Now;
                    logdata.CreatorId = _operator.UserId;
                    logdata.CreatorName = basedata.RealName;
                    logdata.Deleted = false;
                    logdata.OperatorId = _operator.UserId;
                    logdata.State = 3;
                    logdata.OldOrNew = PB_PackListdata.OldOrNew;
                    StockLogList.Add(logdata);

                    //删除库存明细
                    sqlMain += @" delete from IT_LocalDetail where PackId='" + packId + "'; ";

                    //删除PB_Stock
                    sqlMain += @" delete from PB_Stock where PackId='" + packId + "'; ";

                    //修改包的状态为已出库
                    sqlMain += @" update PB_PackList set Status='4',OutStorTime=NOW() where Id='" + packId + "'; ";
                }
            }
            else if (packmodel == "04")
            {
                //获取调拨单要出库的物料信息
                //TD_AllocateDetail AllocateDetaildata = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.Id == allocateId && x.MaterialId == materialId).FirstOrDefaultAsync();
                //获取调拨单的物料明细信息
                Expression<Func<TD_AllocateDetail, TD_AllocatePackDetail, TD_AllocateDetailListDTO>> select = (a, b) => new TD_AllocateDetailListDTO
                {
                    Id = a.Id,
                    AllocateId = a.AllocateId,
                    FromStorId = a.FromStorId,
                    FromlocalId = a.FromLocalId,
                    ToStorId = a.ToStorId,
                    ToLocalId = a.ToLocalId,
                    MaterialId = a.MaterialId,
                    AllocateNum = a.AllocateNum,
                    PackId = b.PackId == null ? "" : b.PackId,
                    PackNums = b.PackNums,
                    JobId = b.JobId == null ? "" : b.JobId
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<TD_AllocateDetail>().AsExpandable()
                        join b in Db.GetIQueryable<TD_AllocatePackDetail>() on a.Id equals b.ParentId into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                var AllDetaillist = await q.Where(x => x.AllocateId == allocateId && x.MaterialId == materialId && x.PackId == "" && x.JobId == "").ToListAsync();
                var AllocateDetaildata = AllDetaillist.GroupBy(x => new { x.Id, x.AllocateId, x.FromStorId, x.FromlocalId, x.ToStorId, x.ToLocalId, x.MaterialId, x.AllocateNum }).Select(x => new
                {
                    Id = x.Key.Id,
                    AllocateId = x.Key.AllocateId,
                    FromStorId = x.Key.FromStorId,
                    FromlocalId = x.Key.FromlocalId,
                    ToStorId = x.Key.ToStorId,
                    ToLocalId = x.Key.ToLocalId,
                    MaterialId = x.Key.MaterialId,
                    AllocateNum = x.Key.AllocateNum,
                    PackNums = x.Sum(n => n.PackNums)
                }).FirstOrDefault();
                //获取库存要出库的物料信息
                List<IT_LocalDetail> IT_LocalDetaillist = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.MaterialId == materialId && x.LocalId == locaId && x.PackId == "" && x.JobId == "").ToListAsync();
                if (IT_LocalDetaillist.Count > 0)
                {
                    //获取要出库的单个物料数量
                    double? warehouseNum = data.Nums;
                    double shengyunum = 0;
                    if (AllocateDetaildata != null)
                    {
                        shengyunum = AllocateDetaildata.AllocateNum - Convert.ToDouble(AllocateDetaildata.PackNums);
                    }
                    //要出库的物料数量和调拨单的物料剩余调拨数量比较
                    if (warehouseNum > shengyunum)
                    {
                        throw new BusException("要出库的物料数量大于调拨单物料的剩余调拨数量");
                    }
                    string strLocalId = string.Empty;
                    string strStorId = string.Empty;
                    foreach (var item in IT_LocalDetaillist)
                    {
                        if (warehouseNum != 0)
                        {
                            strLocalId = item.LocalId;
                            strStorId = item.StorId;
                            //出库数量等于库存明细数量时
                            if (item.Num == warehouseNum)
                            {
                                warehouseNum -= item.Num;
                                if (item.OldOrNew == 0)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                                else if (item.OldOrNew == 1)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                                sqlMain += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                            }
                            else if (item.Num < warehouseNum)   //出库数量大于库存明细数量时
                            {
                                if (warehouseNum >= item.Num)
                                {
                                    warehouseNum -= item.Num;
                                    if (item.OldOrNew == 0)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                    }
                                    else if (item.OldOrNew == 1)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                    }
                                    sqlMain += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                                }
                                else
                                {

                                    if (item.OldOrNew == 0)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                    }
                                    else if (item.OldOrNew == 1)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                    }
                                    sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                                    warehouseNum -= warehouseNum;
                                }
                            }
                            else if (item.Num > warehouseNum) //出库数量小于库存明细数量时
                            {
                                item.Num -= warehouseNum;
                                if (item.OldOrNew == 0)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                                else if (item.OldOrNew == 1)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                                sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                                warehouseNum -= warehouseNum;
                            }

                        }
                        else
                        {
                            continue;
                        }
                    }

                    //添加调拨单包明细
                    TD_AllocatePackDetail tdpackdata = new TD_AllocatePackDetail();
                    tdpackdata.Id = IdHelper.GetId();
                    tdpackdata.ParentId = AllocateDetaildata.Id;
                    tdpackdata.AllocateId = allocateId;
                    tdpackdata.MaterialId = AllocateDetaildata.MaterialId;
                    tdpackdata.PackId = "";
                    tdpackdata.PackNums = data.Nums;
                    tdpackdata.FormLocaId = AllocateDetaildata.FromlocalId;
                    tdpackdata.ToLocaId = "";
                    tdpackdata.Status = 0;
                    tdpackdata.CreateTime = DateTime.Now;
                    tdpackdata.CreatorId = _operator.UserId;
                    tdpackdata.Deleted = false;
                    tdpackdata.OldOrNew = 1;
                    tdpackdata.JobId = "";
                    AllocatePackDetailList.Add(tdpackdata);

                    //增加出库日志
                    PB_StockLog logdata = new PB_StockLog();
                    logdata.Id = IdHelper.GetId();
                    logdata.PackId = "";
                    logdata.MaterialId = AllocateDetaildata.MaterialId;
                    logdata.StorId = AllocateDetaildata.FromStorId;
                    logdata.LocationId = AllocateDetaildata.FromlocalId;
                    logdata.StockNumber = data.Nums;
                    logdata.CreateTime = DateTime.Now;
                    logdata.CreatorId = _operator.UserId;
                    logdata.CreatorName = basedata.RealName;
                    logdata.Deleted = false;
                    logdata.OperatorId = _operator.UserId;
                    logdata.State = 3;
                    logdata.OldOrNew = 1;
                    logdata.JobId = "";
                    StockLogList.Add(logdata);

                    ////获取要出库的单个物料数量
                    //warehouseNum = data.Nums;

                    ////PB_Stock要出库的物料信息
                    //List<PB_Stock> PB_Stocklist = await Db.GetIQueryable<PB_Stock>().Where(x => x.MaterialId == materialId && x.LocationId == AllocateDetaildata.FromlocalId && x.PackId == "" && x.JobId == "").ToListAsync();
                    //if (PB_Stocklist.Count > 0)
                    //{
                    //    foreach (var item in PB_Stocklist)
                    //    {
                    //        if (warehouseNum != 0)
                    //        {
                    //            //出库数量等于库存明细数量时
                    //            if (item.StockNumber == warehouseNum)
                    //            {
                    //                warehouseNum -= item.StockNumber;
                    //                sqlMain += @" delete from PB_Stock where Id='" + item.Id + "'; ";
                    //            }
                    //            else if (item.StockNumber < warehouseNum)   //出库数量大于库存明细数量时
                    //            {
                    //                if (warehouseNum >= item.StockNumber)
                    //                {
                    //                    warehouseNum -= item.StockNumber;
                    //                    sqlMain += @" delete from PB_Stock where Id='" + item.Id + "'; ";
                    //                }
                    //                else
                    //                {
                    //                    sqlMain += @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                    //                    warehouseNum -= warehouseNum;
                    //                }
                    //            }
                    //            else if (item.StockNumber > warehouseNum) //出库数量小于库存明细数量时
                    //            {
                    //                item.StockNumber -= warehouseNum;
                    //                sqlMain += @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                    //                warehouseNum -= warehouseNum;
                    //            }
                    //        }
                    //        else
                    //        {
                    //            continue;
                    //        }
                    //    }
                    //}
                }
                else
                {
                    throw new BusException("请检查库存物料是否满足需求");
                }
            }
            else if (packmodel == "14")
            {
                if (linktypedata.Whether == true)
                {
                    //查询库存是否存在
                    IT_LocalDetail LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.JobId == jobid).FirstOrDefaultAsync();
                    if (LocalDetail != null)
                    {
                        //查询调拨单物料明细信息
                        TD_AllocateDetail tddetaildata = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == allocateId && x.FromLocalId == LocalDetail.LocalId && x.MaterialId == LocalDetail.MaterialId).FirstOrDefaultAsync();
                        if (tddetaildata != null)
                        {
                            //查询调拨单物料
                            List<TD_AllocatePackDetail> lisdata = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.MaterialId == LocalDetail.MaterialId && x.AllocateId == allocateId).ToListAsync();
                            //调拨单物料数量和调拨单物料数量比较
                            double dnum = 0;
                            foreach (var item in lisdata)
                            {
                                dnum += Convert.ToDouble(item.PackNums);
                            }
                            dnum += Convert.ToDouble(LocalDetail.Num);
                            if (dnum <= tddetaildata.AllocateNum)
                            {
                                //添加调拨单包明细
                                TD_AllocatePackDetail tdpackdata = new TD_AllocatePackDetail();
                                tdpackdata.Id = IdHelper.GetId();
                                tdpackdata.ParentId = tddetaildata.Id;
                                tdpackdata.AllocateId = allocateId;
                                tdpackdata.MaterialId = tddetaildata.MaterialId;
                                tdpackdata.PackId = packId;
                                tdpackdata.PackNums = LocalDetail.Num;
                                tdpackdata.FormLocaId = LocalDetail.LocalId;
                                tdpackdata.ToLocaId = "";
                                tdpackdata.Status = 0;
                                tdpackdata.CreateTime = DateTime.Now;
                                tdpackdata.CreatorId = _operator.UserId;
                                tdpackdata.Deleted = false;
                                tdpackdata.OldOrNew = LocalDetail.OldOrNew;
                                tdpackdata.JobId = jobid;
                                AllocatePackDetailList.Add(tdpackdata);

                                //增加出库日志
                                PB_StockLog logdata = new PB_StockLog();
                                logdata.Id = IdHelper.GetId();
                                logdata.PackId = packId;
                                logdata.StorId = LocalDetail.StorId;
                                logdata.LocationId = LocalDetail.LocalId;
                                logdata.StockNumber = LocalDetail.Num;
                                logdata.CreateTime = DateTime.Now;
                                logdata.CreatorId = _operator.UserId;
                                logdata.CreatorName = basedata.RealName;
                                logdata.Deleted = false;
                                logdata.OperatorId = _operator.UserId;
                                logdata.State = 3;
                                logdata.OldOrNew = LocalDetail.OldOrNew;
                                logdata.JobId = jobid;
                                StockLogList.Add(logdata);

                                //删除库存明细
                                sqlMain += @" delete from IT_LocalDetail where JobId='" + jobid + "'; ";

                                //删除PB_Stock
                                sqlMain += @" delete from PB_Stock where JobId='" + jobid + "'; ";

                                //库存汇总减去出库的数量
                                if (LocalDetail.OldOrNew == 0)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-1,ScanNum=IFNULL(ScanNum,0)-1 where StorId='" + LocalDetail.StorId + "' and LocalId='" + LocalDetail.LocalId + "' and MaterialId='" + LocalDetail.MaterialId + "'; ";
                                }
                                else if (LocalDetail.OldOrNew == 1)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-1,ScanNum=IFNULL(ScanNum,0)-1 where StorId='" + LocalDetail.StorId + "' and LocalId='" + LocalDetail.LocalId + "' and MaterialId='" + LocalDetail.MaterialId + "'; ";
                                }
                                //减去物料的审核前数量
                                sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)-1 where Id='" + LocalDetail.MaterialId + "'; ";
                            }
                            else
                            {
                                throw new BusException("要出库的物料数量大于调拨单物料的剩余调拨数量");
                            }
                        }
                        else
                        {
                            throw new BusException("请检查货位,物料信息与调拨单的物料信息是否匹配");
                        }
                    }
                    else
                    {
                        throw new BusException("请检查库存物料是否满足需求");
                    }
                }
                else
                { //查询成品物料信息
                    PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                    if (jobdata == null)
                    {
                        throw new BusException("请检查成品信息是否正确");
                    }
                    //查询仓库内成品物料信息
                    List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.MaterialId == jobdata.MaterialId && x.LocalId == locaId && x.PackId == "").ToListAsync();
                    //获取调拨单物料信息
                    TD_AllocateDetail AllocateDetail = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == allocateId && x.MaterialId == jobdata.MaterialId).FirstOrDefaultAsync();
                    PB_Location locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == locaId).FirstOrDefaultAsync();
                    double? Nums_N = 0;
                    double? Nums_O = 0;
                    //获取要出库的数量
                    double? dnums = data.Nums;
                    foreach (var item in LocalDetail)
                    {
                        if (dnums != 0)
                        {
                            if (item.Num == dnums)
                            {
                                sqlMain += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                                if (item.OldOrNew == 0)
                                {
                                    Nums_O += item.Num;
                                }
                                else if (item.OldOrNew == 1)
                                {
                                    Nums_N += item.Num;
                                }
                                dnums -= item.Num;
                            }
                            else if (item.Num > dnums)
                            {
                                sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + dnums + " where Id='" + item.Id + "'; ";
                                if (item.OldOrNew == 0)
                                {
                                    Nums_O += dnums;
                                }
                                else if (item.OldOrNew == 1)
                                {
                                    Nums_N += dnums;
                                }
                                dnums -= dnums;
                            }
                            else if (item.Num < dnums)
                            {
                                sqlMain += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                                if (item.OldOrNew == 0)
                                {
                                    Nums_O += item.Num;
                                }
                                else if (item.OldOrNew == 1)
                                {
                                    Nums_N += item.Num;
                                }
                                dnums -= item.Num;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                    //修改库存汇总表
                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + Nums_O + ",Nums_N=IFNULL(Nums_N,0)-" + Nums_N + ",ScanNum=IFNULL(ScanNum,0)-" + (Nums_N + Nums_O) + " where  LocalId='" + locaId + "' and MaterialId='" + jobdata.MaterialId + "'; ";
                    //减去物料的审核前数量
                    sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)-" + (Nums_N + Nums_O) + " where Id='" + jobdata.MaterialId + "'; ";
                    //调拨单扫码明细
                    TD_AllocatePackDetail AllocatePackDetail = new TD_AllocatePackDetail();
                    AllocatePackDetail.Id = IdHelper.GetId();
                    AllocatePackDetail.ParentId = AllocateDetail.Id;
                    AllocatePackDetail.AllocateId = allocateId;
                    AllocatePackDetail.MaterialId = jobdata.MaterialId;
                    AllocatePackDetail.PackId = "";
                    AllocatePackDetail.PackNums = data.Nums;
                    AllocatePackDetail.FormLocaId = locaId;
                    AllocatePackDetail.ToLocaId = "";
                    AllocatePackDetail.Status = 0;
                    AllocatePackDetail.CreateTime = DateTime.Now;
                    AllocatePackDetail.CreatorId = _operator.UserId;
                    AllocatePackDetail.Deleted = false;
                    AllocatePackDetail.OldOrNew = jobdata.OldOrNew;
                    AllocatePackDetail.JobId = "";
                    AllocatePackDetailList.Add(AllocatePackDetail);

                    //出库日志
                    PB_StockLog StockLog = new PB_StockLog();
                    StockLog.Id = IdHelper.GetId();
                    StockLog.PackId = "";
                    StockLog.MaterialId = jobdata.MaterialId;
                    StockLog.StorId = locadata.StorId;
                    StockLog.LocationId = locaId;
                    StockLog.StockNumber = data.Nums;
                    StockLog.CreatorId = _operator.UserId;
                    StockLog.Deleted = false;
                    StockLog.CreatorName = basedata.RealName;
                    StockLog.OperatorId = _operator.UserId;
                    StockLog.Type = 1;
                    StockLog.OrderID = allocateId;
                    StockLog.CreateTime = DateTime.Now;
                    StockLog.State = 3;
                    StockLog.OldOrNew = jobdata.OldOrNew;
                    StockLog.CirBillId = "";
                    StockLog.JobId = "";
                    StockLogList.Add(StockLog);
                }
            }

            await Db.InsertAsync<TD_AllocatePackDetail>(AllocatePackDetailList);

            await Db.InsertAsync<PB_StockLog>(StockLogList);

            await Db.InsertAsync<PB_UnpackingDetail>(UnpackingDetailList);

            await Db.InsertAsync<PB_Unpacking>(UnpackingList);

            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 调拨出库获取单个成品物料信息
        /// </summary>
        /// <param name="JobQrCode">成品二维码</param>
        /// <param name="cateqrcode">调拨单二维码</param>
        /// <returns></returns>
        public async Task<AllocateJobMaterialDTO> GetAllocateJobMaterialDataAsync(string JobQrCode, string cateqrcode)
        {
            //成品Id
            string jobid = JobQrCode.Split(',')?[1].ToString();
            //调拨单id
            string cateid = cateqrcode.Split(',')?[1].ToString();
            PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
            if (jobdata != null)
            {
                //获取调拨单物料信息
                TD_AllocateDetail AllocateDetail = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == cateid && x.MaterialId == jobdata.MaterialId).FirstOrDefaultAsync();
                //查询物料信息
                PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobdata.MaterialId).FirstOrDefaultAsync();
                //查询成品物料仓库内的包外的成品物料信息
                List<IT_LocalDetail> LocalDetailList = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.LocalId == AllocateDetail.FromLocalId && x.MaterialId == jobdata.MaterialId && x.PackId == "").ToListAsync();
                if (LocalDetailList.Count > 0)
                {
                    //查询仓库包外物料成品数量
                    var materData = LocalDetailList.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.Num) }).FirstOrDefault();
                    //查询调拨单已出库数量
                    List<TD_AllocatePackDetail> AllocatePackDetail = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.AllocateId == cateid && x.MaterialId == jobdata.MaterialId).ToListAsync();
                    var PackDetail = AllocatePackDetail.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).FirstOrDefault();
                    //查询调拨单已出库的单个成品物料信息
                    var alljobdata = AllocatePackDetail.Where(x => x.PackId == "").ToList();
                    var jobmater = alljobdata.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).FirstOrDefault();

                    AllocateJobMaterialDTO StockMaterial = new AllocateJobMaterialDTO();
                    StockMaterial.MaterialId = materData.MaterialId;
                    StockMaterial.MaterialCode = Material.Code;
                    StockMaterial.MaterialName = Material.Name;
                    StockMaterial.MaterialSpec = Material.Spec;
                    StockMaterial.PackId = "";
                    StockMaterial.PackQrCode = "";
                    StockMaterial.Nums = (materData.Nums - (jobmater == null ? 0 : jobmater.Nums));  //仓库内包外的成品物料数量
                    StockMaterial.RemainingQuantity = (AllocateDetail.AllocateNum - (PackDetail == null ? 0 : PackDetail.Nums));  //剩余数量
                    return StockMaterial;
                }
                else
                {
                    throw new BusException("请检查物料是否在包外或进行扫描包码操作");
                }
            }
            else
            {
                throw new BusException("请检查成品码是否存在");
            }
        }

        /// <summary>
        /// 调拨出入库单个物料
        /// </summary>
        /// <param name="data"></param>
        /// 2022-02-23   赵锦涛
        /// <returns></returns>
        public async Task<AllocateMaterialDTO> GetAllocateDetailMaterialAsync(AllocateDTO data)
        {
            var packmodel = data.packqrcode.Split(',')?[0];
            string packid = string.Empty;
            if (packmodel == "04")
            {
                var model = data.packqrcode.Split(',');
                if (model.Length > 2)
                {
                    if (model.Length < 4)
                    {
                        throw new BusException("请扫描或输入正确的物料二维码");
                    }
                    else
                    {
                        packid = model?[3].ToString();
                    }
                }
                else
                {
                    packid = model?[1].ToString();
                }
            }

            TD_AllocateDetail detaildata = new TD_AllocateDetail();
            if (data.Status == 0)
            {
                detaildata = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == data.cateqrcode.Split(',')[1].ToString() && x.FromLocalId == data.locaqrcode.Split(',')[1].ToString() && x.MaterialId == packid).FirstOrDefaultAsync();
                if (detaildata == null)
                {
                    throw new BusException("请扫描调拨单上要下架的货位上的物料二维码");
                }
            }
            else
            {
                detaildata = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == data.cateqrcode.Split(',')[1].ToString() && x.ToLocalId == data.locaqrcode.Split(',')[1].ToString() && x.MaterialId == packid).FirstOrDefaultAsync();
                if (detaildata == null)
                {
                    throw new BusException("请扫描调拨单上要上架的货位上的物料二维码");
                }
            }
            
            string sqlMain = @"select MaterialId,Code,Name,Spec,(AllocateNum-SUM(IFNULL(PackNums,0))) as AllocateNum from ( select a.MaterialId,c.`Code`,c.`Name`,c.Spec,a.AllocateNum,b.PackNums from TD_AllocateDetail  as a left join TD_AllocatePackDetail as b on a.AllocateId=b.AllocateId and a.MaterialId=b.MaterialId and b.PackId='' and b.`Status`=" + data.Status + " left join PB_Material as c on a.MaterialId=c.Id where a.AllocateId='" + data.cateqrcode.Split(',')[1].ToString() + "' and a.MaterialId='" + packid + "' )as t group by MaterialId,Code,Name,Spec,AllocateNum";
            var listdata = await Db.GetListBySqlAsync<AllocateMaterialDTO>(sqlMain);
            return listdata.FirstOrDefault();
        }

        /// <summary>
        /// 调拨单出库移除
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task DeleteAllocateDetailAsync(AllocatePackDetailDTO data)
        {
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            List<PB_Location> localist = await Db.GetIQueryable<PB_Location>().ToListAsync();
            List<TD_AllocatePackDetail> allocate = new List<TD_AllocatePackDetail>();

            List<PB_Stock> Stocklist = new List<PB_Stock>();
            List<PB_StockLog> Stockloglist = new List<PB_StockLog>();
            List<IT_LocalDetail> LocalDetaillist = new List<IT_LocalDetail>();
            string sqlMain = string.Empty;
            if (data.PackId.IsNullOrEmpty())
            {
                if (data.JobId.IsNullOrEmpty())
                {
                    allocate = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.Id == data.Id && x.JobId == "").ToListAsync();
                    if (allocate.Count == 0)
                    {
                        throw new BusException("已移除不能重复移除");
                    }
                    foreach (var item in allocate)
                    {
                        var locadata = localist.Where(x => x.Id == item.FormLocaId).FirstOrDefault();

                        PB_Stock stockdata = new PB_Stock();
                        stockdata.Id = IdHelper.GetId();
                        stockdata.PackId = "";
                        stockdata.StorId = locadata.StorId;
                        stockdata.LocationId = locadata.Id;
                        stockdata.StockNumber = item.PackNums;
                        stockdata.MaterialId = item.MaterialId;
                        stockdata.CreatorId = _operator.UserId;
                        stockdata.CreatorName = userdata.RealName;
                        stockdata.CreateTime = DateTime.Now;
                        stockdata.OperatorId = _operator.UserId;
                        stockdata.Type = 1;
                        stockdata.OrderID = data.AllocateId;
                        stockdata.OldOrNew = item.OldOrNew;
                        stockdata.AreaId = locadata.AreaId;
                        stockdata.RackId = locadata.RackId;
                        stockdata.JobId = "";
                        Stocklist.Add(stockdata);

                        PB_StockLog stockdatalog = new PB_StockLog();
                        stockdatalog.Id = IdHelper.GetId();
                        stockdatalog.PackId = "";
                        stockdatalog.StorId = locadata.StorId;
                        stockdatalog.LocationId = locadata.Id;
                        stockdatalog.StockNumber = item.PackNums;
                        stockdatalog.MaterialId = item.MaterialId;
                        stockdatalog.CreatorId = _operator.UserId;
                        stockdatalog.CreatorName = userdata.RealName;
                        stockdatalog.CreateTime = DateTime.Now;
                        stockdatalog.OperatorId = _operator.UserId;
                        stockdatalog.Type = 1;
                        stockdatalog.OrderID = data.AllocateId;
                        stockdatalog.OldOrNew = item.OldOrNew;
                        stockdatalog.State = 0;
                        stockdatalog.JobId = "";
                        Stockloglist.Add(stockdatalog);

                        IT_LocalDetail itdata = new IT_LocalDetail();
                        itdata.Id = IdHelper.GetId();
                        itdata.StorId = locadata.StorId;
                        itdata.LocalId = locadata.Id;
                        itdata.MaterialId = item.MaterialId;
                        itdata.MeasureId = "";
                        itdata.BarCode = h_Material + "," + item.MaterialId;
                        itdata.InTime = DateTime.Now;
                        itdata.CreateTime = DateTime.Now;
                        itdata.CreatorId = _operator.UserId;
                        itdata.Deleted = false;
                        itdata.Num = item.PackNums;
                        itdata.PackId = "";
                        itdata.OldOrNew = item.OldOrNew;
                        itdata.JobId = "";
                        LocalDetaillist.Add(itdata);

                        if (item.OldOrNew == 0)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + item.PackNums + ",ScanNum=IFNULL(ScanNum,0)+" + item.PackNums + " where MaterialId='" + item.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                        }
                        else if (item.OldOrNew == 1)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.PackNums + ",ScanNum=IFNULL(ScanNum,0)+" + item.PackNums + " where MaterialId='" + item.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                        }

                        sqlMain += @" DELETE FROM TD_AllocatePackDetail WHERE Id='" + data.Id + "'; ";

                    }
                }
                else
                {
                    TD_AllocatePackDetail AllocatePackDetail = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.Id == data.Id && x.JobId == data.JobId).FirstOrDefaultAsync();
                    if (AllocatePackDetail == null)
                    {
                        throw new BusException("已移除不能重复移除");
                    }
                    var locadata = localist.Where(x => x.Id == AllocatePackDetail.FormLocaId).FirstOrDefault();
                    PB_Stock stockdata = new PB_Stock();
                    stockdata.Id = IdHelper.GetId();
                    stockdata.PackId = "";
                    stockdata.StorId = locadata.StorId;
                    stockdata.LocationId = locadata.Id;
                    stockdata.StockNumber = AllocatePackDetail.PackNums;
                    stockdata.MaterialId = AllocatePackDetail.MaterialId;
                    stockdata.CreatorId = _operator.UserId;
                    stockdata.CreatorName = userdata.RealName;
                    stockdata.CreateTime = DateTime.Now;
                    stockdata.OperatorId = _operator.UserId;
                    stockdata.Type = 1;
                    stockdata.OrderID = data.AllocateId;
                    stockdata.OldOrNew = AllocatePackDetail.OldOrNew;
                    stockdata.AreaId = locadata.AreaId;
                    stockdata.RackId = locadata.RackId;
                    stockdata.JobId = data.JobId;
                    Stocklist.Add(stockdata);

                    PB_StockLog stockdatalog = new PB_StockLog();
                    stockdatalog.Id = IdHelper.GetId();
                    stockdatalog.PackId = "";
                    stockdatalog.StorId = locadata.StorId;
                    stockdatalog.LocationId = locadata.Id;
                    stockdatalog.StockNumber = AllocatePackDetail.PackNums;
                    stockdatalog.MaterialId = AllocatePackDetail.MaterialId;
                    stockdatalog.CreatorId = _operator.UserId;
                    stockdatalog.CreatorName = userdata.RealName;
                    stockdatalog.CreateTime = DateTime.Now;
                    stockdatalog.OperatorId = _operator.UserId;
                    stockdatalog.Type = 1;
                    stockdatalog.OrderID = data.AllocateId;
                    stockdatalog.OldOrNew = AllocatePackDetail.OldOrNew;
                    stockdatalog.State = 0;
                    stockdatalog.JobId = AllocatePackDetail.JobId;
                    Stockloglist.Add(stockdatalog);

                    IT_LocalDetail itdata = new IT_LocalDetail();
                    itdata.Id = IdHelper.GetId();
                    itdata.StorId = locadata.StorId;
                    itdata.LocalId = locadata.Id;
                    itdata.MaterialId = AllocatePackDetail.MaterialId;
                    itdata.MeasureId = "";
                    itdata.BarCode = h_FinishedProduct + "," + AllocatePackDetail.MaterialId;
                    itdata.InTime = DateTime.Now;
                    itdata.CreateTime = DateTime.Now;
                    itdata.CreatorId = _operator.UserId;
                    itdata.Deleted = false;
                    itdata.Num = AllocatePackDetail.PackNums;
                    itdata.PackId = "";
                    itdata.OldOrNew = AllocatePackDetail.OldOrNew;
                    itdata.JobId = AllocatePackDetail.JobId;
                    LocalDetaillist.Add(itdata);

                    if (AllocatePackDetail.OldOrNew == 0)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+1,ScanNum=IFNULL(ScanNum,0)+1 where MaterialId='" + AllocatePackDetail.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                    }
                    else if (AllocatePackDetail.OldOrNew == 1)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+1,ScanNum=IFNULL(ScanNum,0)+1 where MaterialId='" + AllocatePackDetail.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                    }

                    sqlMain += @" DELETE FROM TD_AllocatePackDetail WHERE Id='" + data.Id + "'; ";
                }
            }
            else
            {
                allocate = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.AllocateId == data.AllocateId && x.PackId == data.PackId).ToListAsync();
                if (allocate == null)
                {
                    throw new BusException("已移除不能重复移除");
                }
                //修改包的状态为入库
                sqlMain += @" update PB_PackList set Status=3,OutStorTime=NULL where Id='" + data.PackId + "';  DELETE FROM TD_AllocatePackDetail WHERE AllocateId='" + data.AllocateId + "' AND PackId='" + data.PackId + "' and `Status`=0; ";

                string strStorId = string.Empty;
                string strLocalId = string.Empty;
                string strAreaId = string.Empty;
                string strRackId = string.Empty;
                foreach (var item in allocate)
                {
                    var locadata = localist.Where(x => x.Id == item.FormLocaId).FirstOrDefault();
                    IT_LocalDetail itdata = new IT_LocalDetail();
                    itdata.Id = IdHelper.GetId();
                    itdata.StorId = locadata.StorId;
                    itdata.LocalId = locadata.Id;
                    itdata.MaterialId = item.MaterialId;
                    itdata.MeasureId = "";
                    itdata.BarCode = h_Pack + "," + item.PackId;
                    itdata.InTime = DateTime.Now;
                    itdata.CreateTime = DateTime.Now;
                    itdata.CreatorId = _operator.UserId;
                    itdata.Deleted = false;
                    itdata.Num = item.PackNums;
                    itdata.PackId = item.PackId;
                    itdata.OldOrNew = item.OldOrNew;
                    itdata.JobId = "";
                    LocalDetaillist.Add(itdata);

                    //添加PB_Stock
                    PB_Stock stockdata = new PB_Stock();
                    stockdata.Id = IdHelper.GetId();
                    stockdata.PackId = data.PackId;
                    stockdata.StorId = locadata.StorId;
                    stockdata.LocationId = locadata.Id;
                    stockdata.StockNumber = data.StockNumber;
                    stockdata.MaterialId = data.MaterialId;
                    stockdata.CreatorId = _operator.UserId;
                    stockdata.CreatorName = userdata.RealName;
                    stockdata.CreateTime = DateTime.Now;
                    stockdata.OperatorId = _operator.UserId;
                    stockdata.Type = 1;
                    stockdata.OrderID = data.AllocateId;
                    stockdata.OldOrNew = item.OldOrNew;
                    stockdata.AreaId = locadata.AreaId;
                    stockdata.RackId = locadata.RackId;
                    stockdata.JobId = "";
                    Stocklist.Add(stockdata);

                    //添加PB_StockLog
                    PB_StockLog stockdatalog = new PB_StockLog();
                    stockdatalog.Id = IdHelper.GetId();
                    stockdatalog.PackId = data.PackId;
                    stockdatalog.StorId = locadata.StorId; 
                    stockdatalog.LocationId = locadata.Id; 
                    stockdatalog.StockNumber = data.StockNumber;
                    stockdatalog.MaterialId = data.MaterialId;
                    stockdatalog.CreatorId = _operator.UserId;
                    stockdatalog.CreatorName = userdata.RealName;
                    stockdatalog.CreateTime = DateTime.Now;
                    stockdatalog.OperatorId = _operator.UserId;
                    stockdatalog.Type = 1;
                    stockdatalog.OrderID = data.AllocateId;
                    stockdatalog.OldOrNew = item.OldOrNew;
                    stockdatalog.State = 0;
                    stockdatalog.JobId = "";
                    Stockloglist.Add(stockdatalog);

                    if (item.OldOrNew == 0)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + item.PackNums + ",ScanNum=IFNULL(ScanNum,0)+" + item.PackNums + " where MaterialId='" + item.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                    }
                    else if (item.OldOrNew == 1)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.PackNums + ",ScanNum=IFNULL(ScanNum,0)+" + item.PackNums + " where MaterialId='" + item.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                    }
                }
            }
            await ExecuteSqlAsync(sqlMain);

            await Db.InsertAsync<PB_Stock>(Stocklist);
            await Db.InsertAsync<PB_StockLog>(Stockloglist);
            await Db.InsertAsync<IT_LocalDetail>(LocalDetaillist);
        }

        /// <summary>
        /// 调拨出库提交
        /// </summary>
        /// <param name="cateqrcode">调拨单的二维码</param>
        /// <returns></returns>
        [Transactional]
        public async Task SubmitcateOutStorageAsync(string cateqrcode)
        {
            //调拨单Id
            string allocateId = cateqrcode.Split(',')?[1].ToString();

            //查询调拨单的明细信息
            List<TD_AllocateDetail> listdetail = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == allocateId).ToListAsync();

            //查询调拨单包明细信息
            List<TD_AllocatePackDetail> listpackdata = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.AllocateId == allocateId && x.Status == 0).ToListAsync();
            var tdpackdata = listpackdata.GroupBy(x => new { x.AllocateId, x.ParentId, x.MaterialId }).Select(x => new { AllocateId = x.Key.AllocateId, ParentId = x.Key.ParentId, MaterialId = x.Key.MaterialId, materNums = x.Sum(i => i.PackNums) }).ToList();
            double? dnum = 0;
            //检查是否全部出库
            int index = 0;
            foreach (var item in listdetail)
            {
                var masterdata = tdpackdata.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                if (masterdata != null)
                {
                    dnum = masterdata.materNums;
                }
                if (item.AllocateNum == Convert.ToDouble(dnum))
                {
                    if (index != 1)
                    {
                        index = 2;
                    }
                }
                else
                {
                    index = 1;
                }
            }
            if (index == 1)
            {
                throw new BusException("请核对调拨单是否全部下架出库");
            }

            //出库单Id
            string outstorId = IdHelper.GetId();
            string storid = string.Empty;
            List<TD_OutStorDetail> listdetaildata = new List<TD_OutStorDetail>();
            List<TD_OutStorRecord> listrecord = new List<TD_OutStorRecord>();
            //创建台账集合
            //List<IT_RecordBook> iT_RecordBooks = new List<IT_RecordBook>();
            double doutnum = 0;
            int j = 0;
            foreach (var item in listdetail)
            {
                if (j == 0)
                {
                    storid = item.FromStorId;
                }
                TD_OutStorRecord cord = new TD_OutStorRecord();
                cord.Id = IdHelper.GetId();
                cord.StorId = item.FromStorId;
                cord.OutStorId = outstorId;
                cord.MaterialId = item.MaterialId;
                cord.OutNum = item.AllocateNum;
                cord.Price = item.Price;
                cord.TotalAmt = item.Price * item.AllocateNum;
                cord.OutNum = item.AllocateNum;
                cord.CreateTime = DateTime.Now;
                cord.CreatorId = _operator.UserId;
                cord.Deleted = false;
                listrecord.Add(cord);

                TD_OutStorDetail detail = new TD_OutStorDetail();
                detail.Id = IdHelper.GetId();
                detail.StorId = item.FromStorId;
                detail.OutStorId = outstorId;
                detail.LocalId = item.FromLocalId;
                detail.MaterialId = item.MaterialId;
                detail.Price = item.Price;
                detail.TotalAmt = item.Price * item.AllocateNum;
                detail.OutNum = item.AllocateNum;
                detail.CreateTime = DateTime.Now;
                detail.CreatorId = _operator.UserId;
                detail.Deleted = false;
                listdetaildata.Add(detail);
                j++;
               
                doutnum += item.AllocateNum;
                //IT_RecordBook iT_RecordBook = new IT_RecordBook();
                //iT_RecordBook.Id = IdHelper.GetId();
                //iT_RecordBook.RefCode = item.AllocateId;
                ////调拨出库
                //iT_RecordBook.Type = "AllocateOut";
                //iT_RecordBook.FromStorId = item.FromStorId;
                //iT_RecordBook.FromLocalId = item.FromLocalId;
                //iT_RecordBook.ToStorId = item.ToStorId;
                //iT_RecordBook.ToLocalId = item.ToLocalId;
                //iT_RecordBook.MaterialId = item.MaterialId;
                //iT_RecordBook.MeasureId = "";
                //iT_RecordBook.BarCode = "";
                //iT_RecordBook.BatchNo = "";
                //iT_RecordBook.Num =  item.AllocateNum;
                //iT_RecordBook.CreateTime = DateTime.Now;
                //iT_RecordBook.CreatorId = _operator.UserId;
                //iT_RecordBook.Deleted = false;
                //iT_RecordBooks.Add(iT_RecordBook);
            }
            TD_OutStorage outdata = new TD_OutStorage();
            outdata.Id = outstorId;
            outdata.StorageId = storid;
            outdata.Code = DateTime.Now.ToString("yyyyMMddHHmmss");
            outdata.OutTime = DateTime.Now;
            outdata.OutType = "AllocateOut";
            outdata.RefCode = allocateId;
            outdata.OutNum = doutnum;
            outdata.CreateTime = DateTime.Now;
            outdata.CreatorId = _operator.UserId;
            outdata.Deleted = false;
            outdata.Status = 1;
            outdata.QrCode = h_OutStorage + "," + outstorId;

            await Db.InsertAsync<TD_OutStorRecord>(listrecord);
            await Db.InsertAsync<TD_OutStorDetail>(listdetaildata);
            //await Db.InsertAsync<IT_RecordBook>(iT_RecordBooks);
            await Db.InsertAsync<TD_OutStorage>(outdata);

            string sqlMain = @"update TD_Allocate set State=0 where Id='" + allocateId + "'";
            await ExecuteSqlAsync(sqlMain);

        }

        /// <summary>
        /// 调拨入库
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task UpcateInStorageAsync(AllocateDTO data)
        {
            //调拨单Id
            string allocateId = data.cateqrcode.Split(',')?[1].ToString();
            //货位Id
            string locaId = data.locaqrcode.Split(',')?[1].ToString();
            //包Id
            string packId = string.Empty;
            string materialId = string.Empty;
            string jobid = string.Empty;
            string packmodel = data.packqrcode.Split(',')?[0].ToString();
            Base_LinkType linktypedata = await _opdept.GetLinkType("MaterialCode");
            if (packmodel == "13")
            {
                packId = data.packqrcode.Split(',')?[1].ToString();
            }
            else if (packmodel == "04")
            {
                var model = data.packqrcode.Split(',');
                if (model.Length > 2)
                {
                    if (model.Length < 4)
                    {
                        throw new BusException("请扫描正确的二维码信息");
                    }
                    else
                    {
                        materialId = model?[3].ToString();
                    }
                }
                else
                {
                    materialId = model?[1].ToString();
                }
                //合并重复物料指向新的物料Id
                PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                if (!materdata.TransferId.IsNullOrEmpty())
                {
                    materialId = materdata.TransferId;
                }
            }
            else if (packmodel == "14")
            {
                jobid = data.packqrcode.Split(',')?[1].ToString();
                ////查询单个成品是否绑定包信息
                //PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid && x.PackStatus == 0).FirstOrDefaultAsync();
                //if (jobdata != null)
                //{
                //    if (!jobdata.PackId.IsNullOrEmpty())
                //    {
                //        packmodel = "13";
                //        packId = jobdata.PackId;
                //    }
                //}
            }

            string sqlMain = string.Empty;
            List<PB_StockLog> StockLogList = new List<PB_StockLog>();
            List<PB_Stock> StockList = new List<PB_Stock>();
            List<IT_LocalDetail> LocalDetailList = new List<IT_LocalDetail>();
            List<IT_LocalMaterial> LocalMaterialList = new List<IT_LocalMaterial>();
            List<TD_AllocatePackDetail> AllocatePackDetailList = new List<TD_AllocatePackDetail>();

            //获取登录人信息
            Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            //获取货位信息
            PB_Location locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == locaId).FirstOrDefaultAsync();
            if (packmodel == "13")
            {
                PB_PackList packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId).FirstOrDefaultAsync();
                if (packdata == null)
                {
                    throw new BusException("请扫描正确的包二维码");
                }
                List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).ToListAsync();
                if (LocalDetail.Count > 0)
                {
                    throw new BusException("请勿重复入库");
                }

                if (packdata.PackageType == 0)
                {
                    TD_AllocatePackDetail packdetaildata = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.PackId == packId && x.AllocateId == allocateId && x.Status == 0).FirstOrDefaultAsync();
                    if (packdetaildata != null)
                    {
                        TD_AllocateDetail Detail = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == allocateId && x.MaterialId == packdetaildata.MaterialId).FirstOrDefaultAsync();
                        if (locadata.Id != Detail.ToLocalId)
                        {
                            throw new BusException("入库货位与调拨单目标货位不符");
                        }

                        PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == packdetaildata.MaterialId).FirstOrDefaultAsync();
                        //增加入库日志
                        PB_StockLog logdata = new PB_StockLog();
                        logdata.Id = IdHelper.GetId();
                        logdata.PackId = packId;
                        logdata.StorId = locadata.StorId;
                        logdata.LocationId = locadata.Id;
                        logdata.StockNumber = packdetaildata.PackNums;
                        logdata.CreateTime = DateTime.Now;
                        logdata.CreatorId = _operator.UserId;
                        logdata.CreatorName = basedata.RealName;
                        logdata.Deleted = false;
                        logdata.OperatorId = _operator.UserId;
                        logdata.State = 1;
                        logdata.OldOrNew = packdetaildata.OldOrNew;
                        logdata.OrderID = allocateId;
                        logdata.JobId = "";
                        StockLogList.Add(logdata);

                        PB_Stock stockdata = new PB_Stock();
                        stockdata.Id = IdHelper.GetId();
                        stockdata.PackId = packdetaildata.PackId;
                        stockdata.StorId = locadata.StorId;
                        stockdata.LocationId = locadata.Id;
                        stockdata.StockNumber = packdetaildata.PackNums;
                        stockdata.MaterialId = packdetaildata.MaterialId;
                        stockdata.CreatorId = _operator.UserId;
                        stockdata.CreatorName = basedata.RealName;
                        stockdata.OperatorId = _operator.UserId;
                        stockdata.Type = 3;
                        stockdata.CreateTime = DateTime.Now;
                        stockdata.OldOrNew = packdetaildata.OldOrNew;
                        stockdata.OrderID = allocateId;
                        stockdata.AreaId = locadata.AreaId;
                        stockdata.RackId = locadata.RackId;
                        stockdata.JobId = "";
                        StockList.Add(stockdata);

                        //增加库存明细表
                        IT_LocalDetail itdetail = new IT_LocalDetail();
                        itdetail.Id = IdHelper.GetId();
                        itdetail.StorId = locadata.StorId;
                        itdetail.LocalId = locadata.Id;
                        itdetail.MaterialId = packdetaildata.MaterialId;
                        itdetail.MeasureId = materdata.storageId;
                        itdetail.BarCode = "";
                        itdetail.InTime = DateTime.Now;
                        itdetail.Amount = materdata.Price * packdetaildata.PackNums;
                        itdetail.CreateTime = DateTime.Now;
                        itdetail.CreatorId = _operator.UserId;
                        itdetail.Price = materdata.Price;
                        itdetail.Deleted = false;
                        itdetail.Num = packdetaildata.PackNums;
                        itdetail.PackId = packdetaildata.PackId;
                        itdetail.OldOrNew = packdetaildata.OldOrNew;
                        itdetail.JobId = "";
                        LocalDetailList.Add(itdetail);

                        //查询库存汇总表信息
                        IT_LocalMaterial itmaterdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == packdetaildata.MaterialId && x.StorId == locadata.StorId && x.LocalId == locadata.Id).FirstOrDefaultAsync();
                        if (itmaterdata != null)
                        {
                            //库存汇总减去出库的数量
                            if (packdetaildata.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + packdetaildata.PackNums + ",ScanNum=IFNULL(ScanNum,0)+" + packdetaildata.PackNums + " where StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "' and MaterialId='" + packdetaildata.MaterialId + "'; ";
                            }
                            else if (packdetaildata.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + packdetaildata.PackNums + ",ScanNum=IFNULL(ScanNum,0)+" + packdetaildata.PackNums + " where StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "' and MaterialId='" + packdetaildata.MaterialId + "'; ";
                            }
                        }
                        else
                        {
                            itmaterdata = new IT_LocalMaterial();
                            itmaterdata.Id = IdHelper.GetId();
                            itmaterdata.MaterialId = packdetaildata.MaterialId;
                            itmaterdata.StorId = locadata.StorId;
                            itmaterdata.LocalId = locadata.Id;
                            if (packdetaildata.OldOrNew == 0)
                            {
                                itmaterdata.Nums_O = Convert.ToDouble(packdetaildata.PackNums);
                                itmaterdata.Nums_N = 0;
                            }
                            else if (packdetaildata.OldOrNew == 1)
                            {
                                itmaterdata.Nums_O = 0;
                                itmaterdata.Nums_N = Convert.ToDouble(packdetaildata.PackNums);
                            }
                            itmaterdata.CreatorId = _operator.UserId;
                            itmaterdata.CreateTime = DateTime.Now;
                            itmaterdata.Deleted = false;
                            itmaterdata.AreaId = locadata.AreaId;
                            itmaterdata.RackId = locadata.RackId;
                            itmaterdata.ScanNum = Convert.ToDouble(packdetaildata.PackNums);
                            itmaterdata.CheckNum = 0;
                            LocalMaterialList.Add(itmaterdata);
                        }
                        //添加调拨单包明细
                        TD_AllocatePackDetail tdpackdata = new TD_AllocatePackDetail();
                        tdpackdata.Id = IdHelper.GetId();
                        tdpackdata.ParentId = packdetaildata.ParentId;
                        tdpackdata.AllocateId = allocateId;
                        tdpackdata.MaterialId = packdetaildata.MaterialId;
                        tdpackdata.PackId = packId;
                        tdpackdata.PackNums = packdetaildata.PackNums;
                        tdpackdata.FormLocaId = "";
                        tdpackdata.ToLocaId = locadata.Id;
                        tdpackdata.Status = 1;
                        tdpackdata.CreateTime = DateTime.Now;
                        tdpackdata.CreatorId = _operator.UserId;
                        tdpackdata.Deleted = false;
                        tdpackdata.OldOrNew = packdetaildata.OldOrNew;
                        tdpackdata.JobId = "";
                        AllocatePackDetailList.Add(tdpackdata);

                        //修改包的状态为入库
                        sqlMain += @" update PB_PackList set Status=3,OutStorTime=NULL,InStorTime=NOW() where Id='" + packId + "';   ";

                    }
                    else
                    {
                        throw new BusException("请扫描调拨单下未入库的包信息");
                    }
                }
                else if (packdata.PackageType == 1)
                {
                    //获取调拨单的物料明细信息
                    Expression<Func<TD_AllocatePackDetail, PB_Material, AllocatePackDetailMaterialDTO>> select = (a, b) => new AllocatePackDetailMaterialDTO
                    {
                        Price = b.Price,
                        storageId = b.storageId
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in Db.GetIQueryable<TD_AllocatePackDetail>().AsExpandable()
                            join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            select @select.Invoke(a, b);
                    var alldetaillist = await q.Where(x => x.PackId == packId && x.AllocateId == allocateId && x.Status == 0).ToListAsync();
                    if (alldetaillist.Count > 0)
                    {
                        List<TD_AllocateDetail> AllocateDetaillist = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == allocateId).ToListAsync();

                        foreach (var item in alldetaillist)
                        {
                            var itemdata = AllocateDetaillist.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                            if (locadata.Id != itemdata.ToLocalId)
                            {
                                throw new BusException("入库货位与调拨单目标货位不符");
                            }

                            PB_Stock stockdata = new PB_Stock();
                            stockdata.Id = IdHelper.GetId();
                            stockdata.PackId = item.PackId;
                            stockdata.StorId = locadata.StorId;
                            stockdata.LocationId = locadata.Id;
                            stockdata.StockNumber = item.PackNums;
                            stockdata.MaterialId = item.MaterialId;
                            stockdata.CreatorId = _operator.UserId;
                            stockdata.CreatorName = basedata.RealName;
                            stockdata.OperatorId = _operator.UserId;
                            stockdata.Type = 3;
                            stockdata.OrderID = allocateId;
                            stockdata.CreateTime = DateTime.Now;
                            stockdata.OldOrNew = item.OldOrNew;
                            stockdata.AreaId = locadata.AreaId;
                            stockdata.RackId = locadata.RackId;
                            stockdata.JobId = "";
                            StockList.Add(stockdata);

                            //增加入库日志
                            PB_StockLog logdata = new PB_StockLog();
                            logdata.Id = IdHelper.GetId();
                            logdata.PackId = item.PackId;
                            logdata.StorId = locadata.StorId;
                            logdata.LocationId = locadata.Id;
                            logdata.StockNumber = item.PackNums;
                            logdata.CreateTime = DateTime.Now;
                            logdata.CreatorId = _operator.UserId;
                            logdata.CreatorName = basedata.RealName;
                            logdata.Deleted = false;
                            logdata.OperatorId = _operator.UserId;
                            logdata.State = 1;
                            logdata.OldOrNew = item.OldOrNew;
                            logdata.OrderID = allocateId;
                            logdata.JobId = "";
                            StockLogList.Add(logdata);

                            //增加库存明细表
                            IT_LocalDetail itdetail = new IT_LocalDetail();
                            itdetail.Id = IdHelper.GetId();
                            itdetail.StorId = locadata.StorId;
                            itdetail.LocalId = locadata.Id;
                            itdetail.MaterialId = item.MaterialId;
                            itdetail.MeasureId = item.storageId;
                            itdetail.BarCode = "";
                            itdetail.InTime = DateTime.Now;
                            itdetail.Amount = item.Price * item.PackNums;
                            itdetail.CreateTime = DateTime.Now;
                            itdetail.CreatorId = _operator.UserId;
                            itdetail.Price = item.Price;
                            itdetail.Deleted = false;
                            itdetail.Num = item.PackNums;
                            itdetail.PackId = item.PackId;
                            itdetail.OldOrNew = item.OldOrNew;
                            itdetail.JobId = "";
                            LocalDetailList.Add(itdetail);

                            //查询库存汇总表信息
                            IT_LocalMaterial itmaterdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == item.MaterialId && x.StorId == locadata.StorId && x.LocalId == locadata.Id).FirstOrDefaultAsync();
                            if (itmaterdata != null)
                            {
                                //库存汇总减去出库的数量
                                if (item.OldOrNew == 0)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + item.PackNums + ",ScanNum=IFNULL(ScanNum,0)+" + item.PackNums + " where StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                                else if (item.OldOrNew == 1)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.PackNums + ",ScanNum=IFNULL(ScanNum,0)+" + item.PackNums + " where StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                            }
                            else
                            {
                                itmaterdata = new IT_LocalMaterial();
                                itmaterdata.Id = IdHelper.GetId();
                                itmaterdata.MaterialId = item.MaterialId;
                                itmaterdata.StorId = locadata.StorId;
                                itmaterdata.LocalId = locadata.Id;
                                if (item.OldOrNew == 0)
                                {
                                    itmaterdata.Nums_O = Convert.ToDouble(item.PackNums);
                                    itmaterdata.Nums_N = 0;
                                }
                                else if (item.OldOrNew == 1)
                                {
                                    itmaterdata.Nums_O = 0;
                                    itmaterdata.Nums_N = Convert.ToDouble(item.PackNums);
                                }
                                itmaterdata.CreatorId = _operator.UserId;
                                itmaterdata.CreateTime = DateTime.Now;
                                itmaterdata.Deleted = false;
                                itmaterdata.AreaId = locadata.AreaId;
                                itmaterdata.RackId = locadata.RackId;
                                itmaterdata.ScanNum = Convert.ToDouble(item.PackNums);
                                itmaterdata.CheckNum = 0;
                                LocalMaterialList.Add(itmaterdata);
                            }

                            //添加调拨单包明细
                            TD_AllocatePackDetail tdpackdata = new TD_AllocatePackDetail();
                            tdpackdata.Id = IdHelper.GetId();
                            tdpackdata.ParentId = item.ParentId;
                            tdpackdata.AllocateId = allocateId;
                            tdpackdata.MaterialId = item.MaterialId;
                            tdpackdata.PackId = packId;
                            tdpackdata.PackNums = item.PackNums;
                            tdpackdata.FormLocaId = "";
                            tdpackdata.ToLocaId = locadata.Id;
                            tdpackdata.Status = 1;
                            tdpackdata.CreateTime = DateTime.Now;
                            tdpackdata.CreatorId = _operator.UserId;
                            tdpackdata.Deleted = false;
                            tdpackdata.OldOrNew = item.OldOrNew;
                            tdpackdata.JobId = "";
                            AllocatePackDetailList.Add(tdpackdata);
                            //修改包的状态为入库
                            sqlMain += @" update PB_PackList set Status=3,OutStorTime=NULL,InStorTime=NOW() where Id='" + packId + "';   ";
                        }
                        //await Db.InsertAsync<PB_Stock>(stocklist);
                        //await Db.InsertAsync<PB_StockLog>(loglist);
                        //await Db.InsertAsync<IT_LocalDetail>(LocalDetaillist);
                        //if (LocalMateriallist.Count > 0)
                        //{
                        //    await Db.InsertAsync<IT_LocalMaterial>(LocalMateriallist);
                        //}
                        //await Db.InsertAsync<TD_AllocatePackDetail>(AllocatePackDetaillist);

                    }
                    else
                    {
                        throw new BusException("请扫描调拨单下未入库的包信息");
                    }
                }
            }
            else if (packmodel == "04")
            {
                TD_AllocateDetail Detail = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == allocateId && x.MaterialId == materialId).FirstOrDefaultAsync();
                if (locadata.Id != Detail.ToLocalId)
                {
                    throw new BusException("入库货位与调拨单目标货位不符");
                }
                List<TD_AllocatePackDetail> PackDetail = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.AllocateId == allocateId && x.MaterialId == materialId && x.PackId == "" && x.JobId == "" && x.Status == 1).ToListAsync();
                var PackDetaildata = PackDetail.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).FirstOrDefault();
                if (PackDetaildata != null)
                {
                    if (PackDetaildata.Nums == Detail.AllocateNum)
                    {
                        throw new BusException("请勿重复入库");
                    }
                }
                //添加PB_Stock
                PB_Stock stockdata = new PB_Stock();
                stockdata.Id = IdHelper.GetId();
                stockdata.PackId = "";
                stockdata.StorId = locadata.StorId;
                stockdata.LocationId = locadata.Id;
                stockdata.StockNumber = data.Nums;
                stockdata.MaterialId = materialId;
                stockdata.CreatorId = _operator.UserId;
                stockdata.CreatorName = basedata.RealName;
                stockdata.CreateTime = DateTime.Now;
                stockdata.OperatorId = _operator.UserId;
                stockdata.Type = 1;
                stockdata.OrderID = allocateId;
                stockdata.OldOrNew = 1;
                stockdata.AreaId = locadata.AreaId;
                stockdata.RackId = locadata.RackId;
                stockdata.JobId = "";
                StockList.Add(stockdata);

                //添加PB_StockLog
                PB_StockLog stockdatalog = new PB_StockLog();
                stockdatalog.Id = IdHelper.GetId();
                stockdatalog.PackId = "";
                stockdatalog.StorId = locadata.StorId;
                stockdatalog.LocationId = locadata.Id;
                stockdatalog.StockNumber = data.Nums;
                stockdatalog.MaterialId = materialId;
                stockdatalog.CreatorId = _operator.UserId;
                stockdatalog.CreatorName = basedata.RealName;
                stockdatalog.CreateTime = DateTime.Now;
                stockdatalog.OperatorId = _operator.UserId;
                stockdatalog.Type = 1;
                stockdatalog.OrderID = allocateId;
                stockdatalog.OldOrNew = 1;
                stockdatalog.State = 0;
                stockdatalog.JobId = "";
                StockLogList.Add(stockdatalog);

                IT_LocalDetail itdata = new IT_LocalDetail();
                itdata.Id = IdHelper.GetId();
                itdata.StorId = locadata.StorId;
                itdata.LocalId = locadata.Id;
                itdata.MaterialId = materialId;
                itdata.MeasureId = "";
                itdata.BarCode = h_Material + "," + materialId;
                itdata.InTime = DateTime.Now;
                itdata.CreateTime = DateTime.Now;
                itdata.CreatorId = _operator.UserId;
                itdata.Deleted = false;
                itdata.Num = data.Nums;
                itdata.PackId = "";
                itdata.OldOrNew = 1;
                itdata.JobId = "";
                LocalDetailList.Add(itdata);

                IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == materialId && x.LocalId == locadata.Id && x.StorId == locadata.StorId).FirstOrDefaultAsync();
                if (LocalMaterial == null)
                {
                    LocalMaterial = new IT_LocalMaterial();
                    LocalMaterial.Id = IdHelper.GetId();
                    LocalMaterial.MaterialId = materialId;
                    LocalMaterial.StorId = locadata.StorId;
                    LocalMaterial.LocalId = locadata.Id;
                    LocalMaterial.Nums_O = 0;
                    LocalMaterial.Nums_N = Convert.ToDouble(data.Nums);
                    LocalMaterial.CreatorId = _operator.UserId;
                    LocalMaterial.CreateTime = DateTime.Now;
                    LocalMaterial.Deleted = false;
                    LocalMaterial.AreaId = locadata.AreaId;
                    LocalMaterial.RackId = locadata.RackId;
                    LocalMaterial.ScanNum = Convert.ToDouble(data.Nums);
                    LocalMaterial.CheckNum = 0;
                    LocalMaterialList.Add(LocalMaterial);
                }
                else
                {
                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where MaterialId='" + materialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                }

                //添加调拨单包明细
                TD_AllocatePackDetail tdpackdata = new TD_AllocatePackDetail();
                tdpackdata.Id = IdHelper.GetId();
                tdpackdata.ParentId = Detail.Id;
                tdpackdata.AllocateId = allocateId;
                tdpackdata.MaterialId = materialId;
                tdpackdata.PackId = packId;
                tdpackdata.PackNums = data.Nums;
                tdpackdata.FormLocaId = "";
                tdpackdata.ToLocaId = locadata.Id;
                tdpackdata.Status = 1;
                tdpackdata.CreateTime = DateTime.Now;
                tdpackdata.CreatorId = _operator.UserId;
                tdpackdata.Deleted = false;
                tdpackdata.OldOrNew = 1;
                tdpackdata.JobId = "";
                AllocatePackDetailList.Add(tdpackdata);
            }
            else if (packmodel == "14")
            {
                if (linktypedata.Whether == true)
                {
                    TD_AllocatePackDetail packdetaildata = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.JobId == jobid && x.AllocateId == allocateId && x.Status == 0).FirstOrDefaultAsync();
                    if (packdetaildata != null)
                    {
                        TD_AllocateDetail Detail = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == allocateId && x.MaterialId == packdetaildata.MaterialId).FirstOrDefaultAsync();
                        if (locadata.Id != Detail.ToLocalId)
                        {
                            throw new BusException("入库货位与调拨单目标货位不符");
                        }
                        TD_AllocatePackDetail PackDetail = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.JobId == jobid && x.AllocateId == allocateId && x.Status == 1).FirstOrDefaultAsync();
                        if (PackDetail != null)
                        {
                            throw new BusException("请勿重复入库");
                        }

                        //添加PB_Stock
                        PB_Stock stockdata = new PB_Stock();
                        stockdata.Id = IdHelper.GetId();
                        stockdata.PackId = "";
                        stockdata.StorId = locadata.StorId;
                        stockdata.LocationId = locadata.Id;
                        stockdata.StockNumber = 1;
                        stockdata.MaterialId = packdetaildata.MaterialId;
                        stockdata.CreatorId = _operator.UserId;
                        stockdata.CreatorName = basedata.RealName;
                        stockdata.CreateTime = DateTime.Now;
                        stockdata.OperatorId = _operator.UserId;
                        stockdata.Type = 1;
                        stockdata.OrderID = allocateId;
                        stockdata.OldOrNew = packdetaildata.OldOrNew;
                        stockdata.AreaId = locadata.AreaId;
                        stockdata.RackId = locadata.RackId;
                        stockdata.JobId = jobid;
                        StockList.Add(stockdata);

                        //添加PB_StockLog
                        PB_StockLog stockdatalog = new PB_StockLog();
                        stockdatalog.Id = IdHelper.GetId();
                        stockdatalog.PackId = "";
                        stockdatalog.StorId = locadata.StorId;
                        stockdatalog.LocationId = locadata.Id;
                        stockdatalog.StockNumber = 1;
                        stockdatalog.MaterialId = packdetaildata.MaterialId;
                        stockdatalog.CreatorId = _operator.UserId;
                        stockdatalog.CreatorName = basedata.RealName;
                        stockdatalog.CreateTime = DateTime.Now;
                        stockdatalog.OperatorId = _operator.UserId;
                        stockdatalog.Type = 1;
                        stockdatalog.OrderID = allocateId;
                        stockdatalog.OldOrNew = packdetaildata.OldOrNew;
                        stockdatalog.State = 0;
                        stockdatalog.JobId = jobid;
                        StockLogList.Add(stockdatalog);

                        //库存明细
                        IT_LocalDetail itdata = new IT_LocalDetail();
                        itdata.Id = IdHelper.GetId();
                        itdata.StorId = locadata.StorId;
                        itdata.LocalId = locadata.Id;
                        itdata.MaterialId = packdetaildata.MaterialId;
                        itdata.MeasureId = "";
                        itdata.BarCode = h_FinishedProduct + "," + jobid;
                        itdata.InTime = DateTime.Now;
                        itdata.CreateTime = DateTime.Now;
                        itdata.CreatorId = _operator.UserId;
                        itdata.Deleted = false;
                        itdata.Num = 1;
                        itdata.PackId = "";
                        itdata.OldOrNew = packdetaildata.OldOrNew;
                        itdata.JobId = jobid;
                        LocalDetailList.Add(itdata);

                        //查询库存汇总
                        IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == packdetaildata.MaterialId && x.LocalId == locaId).FirstOrDefaultAsync();
                        if (LocalMaterial != null)
                        {
                            if (packdetaildata.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where MaterialId='" + materialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                            }
                            else if (packdetaildata.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where MaterialId='" + materialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                            }
                        }
                        else
                        {
                            LocalMaterial = new IT_LocalMaterial();
                            LocalMaterial.Id = IdHelper.GetId();
                            LocalMaterial.MaterialId = packdetaildata.MaterialId;
                            LocalMaterial.StorId = locadata.StorId;
                            LocalMaterial.LocalId = locadata.Id;
                            if (packdetaildata.OldOrNew == 0)
                            {
                                LocalMaterial.Nums_O = 1;
                                LocalMaterial.Nums_N = 0;
                            }
                            else if (packdetaildata.OldOrNew == 1)
                            {
                                LocalMaterial.Nums_O = 0;
                                LocalMaterial.Nums_N = 1;
                            }
                            LocalMaterial.CreatorId = _operator.UserId;
                            LocalMaterial.CreateTime = DateTime.Now;
                            LocalMaterial.Deleted = false;
                            LocalMaterial.AreaId = locadata.AreaId;
                            LocalMaterial.RackId = locadata.RackId;
                            LocalMaterial.ScanNum = Convert.ToDouble(data.Nums);
                            LocalMaterial.CheckNum = 0;
                            LocalMaterialList.Add(LocalMaterial);

                        }

                        //添加调拨单包明细
                        TD_AllocatePackDetail tdpackdata = new TD_AllocatePackDetail();
                        tdpackdata.Id = IdHelper.GetId();
                        tdpackdata.ParentId = Detail.Id;
                        tdpackdata.AllocateId = allocateId;
                        tdpackdata.MaterialId = packdetaildata.MaterialId;
                        tdpackdata.PackId = "";
                        tdpackdata.PackNums = 1;
                        tdpackdata.FormLocaId = "";
                        tdpackdata.ToLocaId = locadata.Id;
                        tdpackdata.Status = 1;
                        tdpackdata.CreateTime = DateTime.Now;
                        tdpackdata.CreatorId = _operator.UserId;
                        tdpackdata.Deleted = false;
                        tdpackdata.OldOrNew = 1;
                        tdpackdata.JobId = jobid;
                        AllocatePackDetailList.Add(tdpackdata);
                    }
                    else
                    {
                        throw new BusException("请扫描调拨单下未入库的成品信息");
                    }
                }
                else
                {
                    //查询成品物料信息
                    PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                    if (jobdata == null)
                    {
                        throw new BusException("请检查成品信息是否正确");
                    }
                    TD_AllocateDetail AllocateDetail = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == allocateId && x.MaterialId == jobdata.MaterialId).FirstOrDefaultAsync();

                    PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobdata.MaterialId).FirstOrDefaultAsync();

                    TD_AllocatePackDetail AllocatePackDetail = new TD_AllocatePackDetail();
                    AllocatePackDetail.Id = IdHelper.GetId();
                    AllocatePackDetail.ParentId = AllocateDetail.Id;
                    AllocatePackDetail.AllocateId = allocateId;
                    AllocatePackDetail.MaterialId = jobdata.MaterialId;
                    AllocatePackDetail.PackId = "";
                    AllocatePackDetail.PackNums = data.Nums;
                    AllocatePackDetail.FormLocaId = "";
                    AllocatePackDetail.ToLocaId = locaId;
                    AllocatePackDetail.Status = 1;
                    AllocatePackDetail.CreateTime = DateTime.Now;
                    AllocatePackDetail.CreatorId = _operator.UserId;
                    AllocatePackDetail.Deleted = false;
                    AllocatePackDetail.OldOrNew = jobdata.OldOrNew;
                    AllocatePackDetail.JobId = "";
                    AllocatePackDetailList.Add(AllocatePackDetail);

                    PB_StockLog StockLog = new PB_StockLog();
                    StockLog.Id = IdHelper.GetId();
                    StockLog.PackId = "";
                    StockLog.MaterialId = jobdata.MaterialId;
                    StockLog.LocationId = locaId;
                    StockLog.StockNumber = data.Nums;
                    StockLog.CreatorId = _operator.UserId;
                    StockLog.Deleted = false;
                    StockLog.CreatorName = basedata.RealName;
                    StockLog.OperatorId = _operator.UserId;
                    StockLog.Type = 1;
                    StockLog.OrderID = allocateId;
                    StockLog.CreateTime = DateTime.Now;
                    StockLog.State = 4;
                    StockLog.OldOrNew = jobdata.OldOrNew;
                    StockLog.CirBillId = "";
                    StockLog.JobId = "";
                    StockLogList.Add(StockLog);

                    IT_LocalDetail LocalDetail = new IT_LocalDetail();
                    LocalDetail.Id = IdHelper.GetId();
                    LocalDetail.StorId = AllocateDetail.ToStorId;
                    LocalDetail.LocalId = locaId;
                    LocalDetail.MaterialId = jobdata.MaterialId;
                    LocalDetail.MeasureId = Material.storageId;
                    LocalDetail.BarCode = h_Material + "," + jobdata.MaterialId;
                    LocalDetail.InTime = DateTime.Now;
                    LocalDetail.Amount = data.Nums * Material.Price;
                    LocalDetail.CreateTime = DateTime.Now;
                    LocalDetail.CreatorId = _operator.UserId;
                    LocalDetail.Price = Material.Price;
                    LocalDetail.Deleted = false;
                    LocalDetail.Num = data.Nums;
                    LocalDetail.PackId = "";
                    LocalDetail.OldOrNew = jobdata.OldOrNew;
                    LocalDetail.RecId = "";
                    LocalDetail.JobId = "";
                    LocalDetailList.Add(LocalDetail);

                    IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == jobdata.MaterialId && x.LocalId == locaId).FirstOrDefaultAsync();
                    if (LocalMaterial != null)
                    {
                        if (jobdata.OldOrNew == 0)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where MaterialId='" + jobdata.MaterialId + "' and LocalId='" + locaId + "'; ";
                        }
                        else if (jobdata.OldOrNew == 1)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where MaterialId='" + jobdata.MaterialId + "' and LocalId='" + locaId + "'; ";
                        }
                    }
                    else
                    {
                        LocalMaterial = new IT_LocalMaterial();
                        LocalMaterial.Id = IdHelper.GetId();
                        LocalMaterial.MaterialId = jobdata.MaterialId;
                        LocalMaterial.StorId = locadata.StorId;
                        LocalMaterial.LocalId = locadata.Id;
                        if (jobdata.OldOrNew == 0)
                        {
                            LocalMaterial.Nums_O = 1;
                            LocalMaterial.Nums_N = 0;
                        }
                        else if (jobdata.OldOrNew == 1)
                        {
                            LocalMaterial.Nums_O = 0;
                            LocalMaterial.Nums_N = 1;
                        }
                        LocalMaterial.CreatorId = _operator.UserId;
                        LocalMaterial.CreateTime = DateTime.Now;
                        LocalMaterial.Deleted = false;
                        LocalMaterial.AreaId = locadata.AreaId;
                        LocalMaterial.RackId = locadata.RackId;
                        LocalMaterial.ScanNum = Convert.ToDouble(data.Nums);
                        LocalMaterial.CheckNum = 0;
                        LocalMaterialList.Add(LocalMaterial);
                    }
                }
            }

            await Db.InsertAsync<PB_StockLog>(StockLogList);
            await Db.InsertAsync<PB_Stock>(StockList);
            await Db.InsertAsync<IT_LocalDetail>(LocalDetailList);
            await Db.InsertAsync<IT_LocalMaterial>(LocalMaterialList);
            await Db.InsertAsync<TD_AllocatePackDetail>(AllocatePackDetailList);

            if (sqlMain.Length > 0)
            {
                await ExecuteSqlAsync(sqlMain);
            }
        }

        /// <summary>
        /// 调拨入库获取单个成品物料信息
        /// </summary>
        /// <param name="JobQrCode">成品二维码</param>
        /// <param name="cateqrcode">调拨单二维码</param>
        /// <returns></returns>
        public async Task<AllocateJobMaterialDTO> GetInAllocateJobMaterialDataAsync(string JobQrCode, string cateqrcode)
        {
            //成品Id
            string jobid = JobQrCode.Split(',')?[1].ToString();
            //调拨单Id
            string allocateId = cateqrcode.Split(',')?[1].ToString();
            PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
            if (jobdata != null)
            {
                //查询调拨单物料已出库信息
                List<TD_AllocatePackDetail> AllocatePackDetailList = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.AllocateId == allocateId && x.MaterialId == jobdata.MaterialId && x.Status == 0).ToListAsync();
                var allmaterial = AllocatePackDetailList.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).FirstOrDefault();
                PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobdata.MaterialId).FirstOrDefaultAsync();
                //查询调拨单已出库的物料信息
                List<TD_AllocatePackDetail> AllocatePackDetailData = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.AllocateId == allocateId && x.MaterialId == jobdata.MaterialId && x.Status == 0 && x.PackId == "").ToListAsync();
                var packdetail = AllocatePackDetailData.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).FirstOrDefault();
                //查询调拨单已入库物料信息
                List<TD_AllocatePackDetail> AllocatePackDetail = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.AllocateId == allocateId && x.MaterialId == jobdata.MaterialId && x.Status == 1).ToListAsync();
                var allpackdata = AllocatePackDetail.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).FirstOrDefault();
                //查询调拨单已入库散件物料信息
                List<TD_AllocatePackDetail> InAllocatePackDetail = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.AllocateId == allocateId && x.MaterialId == jobdata.MaterialId && x.Status == 1 && x.PackId == "").ToListAsync();
                var Inallpackdata = InAllocatePackDetail.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).FirstOrDefault();

                AllocateJobMaterialDTO StockMaterial = new AllocateJobMaterialDTO();
                StockMaterial.MaterialId = jobdata.MaterialId;
                StockMaterial.MaterialCode = Material.Code;
                StockMaterial.MaterialName = Material.Name;
                StockMaterial.MaterialSpec = Material.Spec;
                StockMaterial.PackId = "";
                StockMaterial.PackQrCode = "";
                StockMaterial.Nums = (packdetail.Nums - (Inallpackdata == null ? 0 : Inallpackdata.Nums));  //仓库内包外的成品物料数量
                StockMaterial.RemainingQuantity = (allmaterial.Nums - (allpackdata == null ? 0 : allpackdata.Nums));  //剩余数量
                return StockMaterial;
            }
            else
            {
                throw new BusException("请检查成品码是否存在");
            }
        }

        /// <summary>
        /// 调拨单入库移除
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task DeleteAllocateWarehousingAsync(AllocatePackDetailDTO data)
        {
            Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            string sqlMain = string.Empty;
            if (data.PackId.IsNullOrEmpty())
            {
                if (data.JobId.IsNullOrEmpty())
                {
                    //删除pb_stock
                    sqlMain += @" delete from PB_Stock where OrderId='" + data.AllocateId + "' and PackId='' and MaterialId='" + data.MaterialId + "' and StockNumber='" + data.StockNumber + "'; ";
                    TD_AllocatePackDetail alldetail = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.Id == data.Id && x.Status == 1).FirstOrDefaultAsync();
                    if (alldetail == null)
                    {
                        throw new BusException("已移除不能重复移除");
                    }
                    PB_Location locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == alldetail.ToLocaId).FirstOrDefaultAsync();
                    //添加PB_StockLog
                    PB_StockLog stockdatalog = new PB_StockLog();
                    stockdatalog.Id = IdHelper.GetId();
                    stockdatalog.PackId = "";
                    stockdatalog.StorId = locadata.StorId;
                    stockdatalog.LocationId = locadata.Id;
                    stockdatalog.StockNumber = alldetail.PackNums;
                    stockdatalog.MaterialId = alldetail.MaterialId;
                    stockdatalog.CreatorId = _operator.UserId;
                    stockdatalog.CreatorName = basedata.RealName;
                    stockdatalog.CreateTime = DateTime.Now;
                    stockdatalog.OperatorId = _operator.UserId;
                    stockdatalog.Type = 1;
                    stockdatalog.OrderID = data.AllocateId;
                    stockdatalog.OldOrNew = alldetail.OldOrNew;
                    stockdatalog.State = 1;

                    //删除库存明细
                    sqlMain += @" delete from IT_LocalDetail where MaterialId='" + alldetail.MaterialId + "' and LocalId='" + alldetail.ToLocaId + "' and Num='" + alldetail.PackNums + "' LIMIT 1; ";
                    //删除库存汇总
                    if (alldetail.OldOrNew == 0)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + alldetail.PackNums + ",ScanNum=IFNULL(ScanNum,0)-" + alldetail.PackNums + " where MaterialId='" + alldetail.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                    }
                    else if (alldetail.OldOrNew == 1)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + alldetail.PackNums + ",ScanNum=IFNULL(ScanNum,0)-" + alldetail.PackNums + " where MaterialId='" + alldetail.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                    }
                    sqlMain += @" DELETE FROM  TD_AllocatePackDetail WHERE Id='" + data.Id + "'; ";
                    await ExecuteSqlAsync(sqlMain);
                    await Db.InsertAsync<PB_StockLog>(stockdatalog);
                }
                else
                {
                    TD_AllocatePackDetail AllocatePackDetail = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.Id == data.Id && x.JobId == data.JobId && x.Status == 1).FirstOrDefaultAsync();
                    if (AllocatePackDetail == null)
                    {
                        throw new BusException("已移除不能重复移除");
                    }
                    PB_Location locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == AllocatePackDetail.ToLocaId).FirstOrDefaultAsync();
                    //添加PB_StockLog
                    PB_StockLog stockdatalog = new PB_StockLog();
                    stockdatalog.Id = IdHelper.GetId();
                    stockdatalog.PackId = "";
                    stockdatalog.StorId = locadata.StorId;
                    stockdatalog.LocationId = locadata.Id;
                    stockdatalog.StockNumber = AllocatePackDetail.PackNums;
                    stockdatalog.MaterialId = AllocatePackDetail.MaterialId;
                    stockdatalog.CreatorId = _operator.UserId;
                    stockdatalog.CreatorName = basedata.RealName;
                    stockdatalog.CreateTime = DateTime.Now;
                    stockdatalog.OperatorId = _operator.UserId;
                    stockdatalog.Type = 1;
                    stockdatalog.OrderID = data.AllocateId;
                    stockdatalog.OldOrNew = AllocatePackDetail.OldOrNew;
                    stockdatalog.State = 1;

                    sqlMain += @"  delete from IT_LocalDetail where JobId='" + data.JobId + "'; ";
                    //删除库存汇总
                    if (AllocatePackDetail.OldOrNew == 0)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + AllocatePackDetail.PackNums + ",ScanNum=IFNULL(ScanNum,0)-" + AllocatePackDetail.PackNums + " where MaterialId='" + AllocatePackDetail.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                    }
                    else if (AllocatePackDetail.OldOrNew == 1)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + AllocatePackDetail.PackNums + ",ScanNum=IFNULL(ScanNum,0)-" + AllocatePackDetail.PackNums + " where MaterialId='" + AllocatePackDetail.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                    }
                    sqlMain += @" DELETE FROM  TD_AllocatePackDetail WHERE Id='" + data.Id + "'; ";
                    await ExecuteSqlAsync(sqlMain);
                    await Db.InsertAsync<PB_StockLog>(stockdatalog);
                }
            }
            else
            {
                List<PB_StockLog> loglist = new List<PB_StockLog>();
                //删除pb_stock
                sqlMain += @" delete from PB_Stock where PackId='"+ data.PackId +"' ; ";
                List<TD_AllocatePackDetail> alldetail = await Db.GetIQueryable<TD_AllocatePackDetail>().Where(x => x.PackId == data.PackId && x.AllocateId == data.AllocateId && x.Status == 1).ToListAsync();
                List<PB_Location> localist = await Db.GetIQueryable<PB_Location>().ToListAsync();
                foreach (var item in alldetail)
                {
                    var locadata = localist.Where(x => x.Id == item.ToLocaId).FirstOrDefault();

                    PB_StockLog stockdatalog = new PB_StockLog();
                    stockdatalog.Id = IdHelper.GetId();
                    stockdatalog.PackId = item.PackId;
                    stockdatalog.StorId = locadata.StorId;
                    stockdatalog.LocationId = locadata.Id;
                    stockdatalog.StockNumber = item.PackNums;
                    stockdatalog.MaterialId = item.MaterialId;
                    stockdatalog.CreatorId = _operator.UserId;
                    stockdatalog.CreatorName = basedata.RealName;
                    stockdatalog.CreateTime = DateTime.Now;
                    stockdatalog.OperatorId = _operator.UserId;
                    stockdatalog.Type = 1;
                    stockdatalog.OrderID = data.AllocateId;
                    stockdatalog.OldOrNew = item.OldOrNew;
                    stockdatalog.State = 1;
                    loglist.Add(stockdatalog);

                    if (item.OldOrNew == 0)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.PackNums + ",ScanNum=IFNULL(ScanNum,0)-" + item.PackNums + " where MaterialId='" + item.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                    }
                    else if (item.OldOrNew == 1)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.PackNums + ",ScanNum=IFNULL(ScanNum,0)-" + item.PackNums + " where MaterialId='" + item.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + locadata.Id + "'; ";
                    }
                }
                //删除IT_LocalDetail
                sqlMain += @"  DELETE FROM IT_LocalDetail WHERE PackId='" + data.PackId + "'; ";
                //删除TD_AllocatePackDetail
                sqlMain += @"  DELETE FROM  TD_AllocatePackDetail WHERE  PackId='" + data.PackId + "' AND Status=1;  ";
                //修改包的状态
                sqlMain += @" update PB_PackList set Status=4,OutStorTime=NOW() where Id='" + data.PackId + "';   ";
                await ExecuteSqlAsync(sqlMain);

                await Db.InsertAsync<PB_StockLog>(loglist);

            }
        }

        /// <summary>
        /// 调拨入库提交
        /// </summary>
        /// <param name="cateqrcode">调拨单的二维码</param>
        /// <returns></returns>
        [Transactional]
        public async Task SubmitcateInStorageAsync(string cateqrcode)
        {
            //调拨单Id
            string allocateId = cateqrcode.Split(',')?[1].ToString();

            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            //查询调拨单的明细信息
            List<TD_AllocateDetail> listdetail = await Db.GetIQueryable<TD_AllocateDetail>().Where(x => x.AllocateId == allocateId).ToListAsync();

            //查询调拨单包明细信息
            Expression<Func<TD_AllocatePackDetail, TD_AllocateDetail, PB_PackList, TD_AllocatePackDetailInStorageDTO>> select = (a, b, c) => new TD_AllocatePackDetailInStorageDTO
            {
                ToStorId = b.ToStorId,
                ToLocalId = b.ToLocalId,
                Price = b.Price,

            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<TD_AllocatePackDetail>().AsExpandable()
                    join b in Db.GetIQueryable<TD_AllocateDetail>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_PackList>() on a.PackId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            List<TD_AllocatePackDetailInStorageDTO> listpackdata = await q.Where(x => x.AllocateId == allocateId && x.Status == 1).ToListAsync();
            var tdpackdata = listpackdata.GroupBy(x => new { x.AllocateId, x.ParentId, x.MaterialId }).Select(x => new { AllocateId = x.Key.AllocateId, ParentId = x.Key.ParentId, MaterialId = x.Key.MaterialId, materNums = x.Sum(i => i.PackNums) }).ToList();
            double? dnum = 0;
            //检查是否全部出库
            int index = 0;
            foreach (var item in listdetail)
            {
                var masterdata = tdpackdata.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                if (masterdata != null)
                {
                    dnum = masterdata.materNums;
                }
                if (item.AllocateNum == Convert.ToDouble(dnum))
                {
                    if (index != 1)
                    {
                        index = 2;
                    }
                }
                else
                {
                    index = 1;
                }
            }
            if (index == 1)
            {
                throw new BusException("请核对调拨单是否全部入库");
            }

            //入库单Id
            string instorId = IdHelper.GetId();
            string storid = string.Empty;
            List<TD_InStorDetail> listdetaildata = new List<TD_InStorDetail>();
            //List<IT_RecordBook> iT_RecordBooks = new List<IT_RecordBook>();
            List<TD_InStorRecord> listrecord = new List<TD_InStorRecord>();
            double? doutnum = 0;
            int j = 0;
            foreach (var item in listdetail)
            {
                if (j == 0)
                {
                    storid = item.FromStorId;
                }
                TD_InStorRecord cord = new TD_InStorRecord();
                cord.Id = IdHelper.GetId();
                cord.InStorId = instorId;
                cord.StorId = storid;
                cord.MaterialId = item.MaterialId;
                cord.Price = item.Price;
                cord.TotalAmt = item.Amount;
                cord.Num = item.AllocateNum;
                cord.CreateTime = DateTime.Now;
                cord.CreatorId = _operator.UserId;
                cord.Deleted = false;
                listrecord.Add(cord);
                    //IT_RecordBook iT_RecordBook= new IT_RecordBook();
                    //iT_RecordBook.Id = IdHelper.GetId();
                    //iT_RecordBook.RefCode = item.AllocateId;
                    //iT_RecordBook.Type = "AllocateIn";
                    //iT_RecordBook.FromStorId = item.FromStorId;
                    //iT_RecordBook.FromLocalId = item.FromLocalId;
                    //iT_RecordBook.ToStorId = item.ToStorId;
                    //iT_RecordBook.ToLocalId = item.ToLocalId;
                    //iT_RecordBook.MaterialId = item.MaterialId;
                    //iT_RecordBook.MeasureId = "";
                    //iT_RecordBook.BarCode = "";
                    //iT_RecordBook.BatchNo = "";
                    //iT_RecordBook.Num = item.AllocateNum;
                    //iT_RecordBook.CreateTime = DateTime.Now;
                    //iT_RecordBook.CreatorId = _operator.UserId;
                    //iT_RecordBook.Deleted = false;
                    //iT_RecordBooks.Add(iT_RecordBook);
                j++;
            }
            foreach (var item in listpackdata)
            {
                TD_InStorDetail instor = new TD_InStorDetail();
                instor.Id = IdHelper.GetId();
                instor.InStorId = instorId;
                instor.StorId = item.ToStorId;
                instor.LocalId = item.ToLocaId;
                instor.MaterialId = item.MaterialId;
                instor.Price = Convert.ToDouble(item.Price);
                instor.TotalAmt = Convert.ToDouble(item.PackNums * item.Price);
                instor.Num = Convert.ToDouble(item.PackNums);
                instor.CreateTime = DateTime.Now;
                instor.CreatorId = _operator.UserId;
                instor.Deleted = false;
                instor.PackId = item.PackId == null ? "" : item.PackId;
                instor.OldOrNew = item.OldOrNew;
                instor.JobId = item.JobId == null ? "" : item.JobId;
                listdetaildata.Add(instor);
                doutnum += item.PackNums;
            }
            //生成入库单
            TD_InStorage InStoragedata = new TD_InStorage();
            InStoragedata.Id = instorId;
            InStoragedata.StorId = storid;
            InStoragedata.Code = GetTimeStamp();
            InStoragedata.InStorTime = DateTime.Now;
            InStoragedata.InType = "AllocateIn";  //调拨入库
            InStoragedata.RefCode = allocateId;   //关联单号
            InStoragedata.Status = 1;  //已审核
            InStoragedata.TotalNum = Convert.ToDouble(doutnum);
            InStoragedata.TotalAmt = 0;
            InStoragedata.CreateTime = DateTime.Now;
            InStoragedata.CreatorId = _operator.UserId;
            InStoragedata.Deleted = false;
            InStoragedata.QrCode = h_Warehousing + "," + instorId;
            InStoragedata.DepId = userdata.DepartmentId;

            await Db.InsertAsync<TD_InStorRecord>(listrecord);
            await Db.InsertAsync<TD_InStorDetail>(listdetaildata);
            //await Db.InsertAsync<IT_RecordBook>(iT_RecordBooks);
            await Db.InsertAsync<TD_InStorage>(InStoragedata);

            string sqlMain = @"update TD_Allocate set State=1,Status=4 where Id='" + allocateId + "'";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 获取调拨入库的仓库货位
        /// </summary>
        /// <param name="storId">仓库id</param>
        /// <param name="locationqrcode">货位二维码</param>
        /// <returns></returns>
        public async Task<PB_Location> GetLocation(string storId, string locationqrcode)
        {
            PB_Location locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.StorId == storId && x.Id==locationqrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
            if (locadata != null)
            {
                return locadata;
            }
            else
            {
                throw new BusException("请扫描调拨单要入库的货位信息");
            }
        }


        public async  Task<TD_AllocateListInfo> GetAllocateListInfoPrint(string ParentId)
        {
            Expression<Func<TD_Allocate, Base_Department,Base_Department,PB_Equipment,PB_Location ,TD_AllocateListInfo>> select = (a, b,c, d,e) => new TD_AllocateListInfo
            {
                StorName = b.Name,
                ToStorName = c.Name,
              EquName=d.Name,
              ToLocaName=e.Name,

            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.StorId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on a.ToStorId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Equipment>() on a.EquId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Location>() on a.ToLocalId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    select @select.Invoke(a,b,c,d,e);
            TD_AllocateListInfo listdata = new TD_AllocateListInfo();
            var qdata = await q.Where(x=>x.Id==ParentId).FirstOrDefaultAsync();
            Expression<Func<TD_AllocateDetail, Base_Department, PB_Location, PB_Tray, PB_TrayZone, Base_Department, PB_Location, PB_Material,PB_StorArea,PB_StorArea,PB_Rack, PB_Rack,TD_AllocateDetaillist>> selects = (a, b, c, d, e, f, g, h,l,m,j,r) => new TD_AllocateDetaillist
            {
                FromStorName = b.Name,///原仓库
                FromLocalName = c.Name,//原货位
                FromTrayName = d.Name,
                FromZoneNmae = e.Name,
                ToStorName = f.Name,
                ToLocalName = g.Name,
                MaterialName = h.Name,
                Spec = h.Spec,
                FromAreaName=l.Name,
                ToAreaNmae=m.Name,
                FoatRackName=j.Name,
                ToRackName=r.Name,
            };
            selects = selects.BuildExtendSelectExpre();
            var k = from a in Db.GetIQueryable<TD_AllocateDetail>().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.FromStorId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Location>() on a.FromLocalId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Tray>() on a.FromTrayId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_TrayZone>() on a.FromZoneId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<Base_Department>() on a.ToStorId equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    join g in Db.GetIQueryable<PB_Location>() on a. ToLocalId equals g.Id into ag
                    from g in ag.DefaultIfEmpty()
                    join h in Db.GetIQueryable<PB_Material>() on a.MaterialId equals h.Id into ah
                    from h in ah.DefaultIfEmpty()
                    join l in Db.GetIQueryable<PB_StorArea>() on c.AreaId equals l.Id into  cl
                    from l in cl.DefaultIfEmpty()
                    join m in Db.GetIQueryable<PB_StorArea>() on g.AreaId equals m.Id into gm
                    from m in gm.DefaultIfEmpty()
                    join j in Db.GetIQueryable<PB_Rack>() on c.RackId equals j.Id into cj
                    from j in cj.DefaultIfEmpty()
                    join r in Db.GetIQueryable<PB_Rack>() on g.RackId equals r.Id into gr
                    from r in gr.DefaultIfEmpty()
                    select @selects.Invoke(a, b, c, d, e, f, g,h,l,m,j,r);
            k = k.Where(h=>h.AllocateId==ParentId);
            var res = await k.ToListAsync();
            TD_AllocateListInfo pblis = new TD_AllocateListInfo();
            pblis.Id = qdata.Id;
            pblis.Code = qdata.Code;
            pblis.AllocateTime = qdata.AllocateTime;
            pblis.Type = qdata.Type;
            pblis.StorId = qdata.StorId;
            pblis.ToStorId = qdata.ToStorId;
            pblis.ToLocalId = qdata.ToLocalId;
            pblis.StorName = qdata.StorName;
            pblis.RefCode = qdata.RefCode;
            pblis.Amount = qdata.Amount;
            pblis.AllocateNum = qdata.AllocateNum;
            pblis.EquId = qdata.EquId;
            pblis.Status = qdata.Status;
            pblis.Remarks=qdata.Remarks;
            pblis.AuditUserId = qdata.AuditUserId;
            pblis.AuditeTime = qdata.AuditeTime;
            pblis.CreateTime = qdata.CreateTime;
            pblis.StorName = qdata.StorName;
            pblis.ToStorName = qdata.ToStorName;
            pblis.EquName = qdata.EquName;
            pblis.ToLocaName = qdata.ToLocaName;
            pblis.QrCode = qdata.QrCode;
            pblis.SubData = res;
            if (res != null)
            {
                return pblis;
            }
            else {
                throw new BusException("暂无数据");
            }
        }

        #endregion

        #region 私有成员

        #endregion
    }
}